如何处理这两个词典以获得Python中的新词典?
我有这两本字典如何处理这两个词典以获得Python中的新词典?,python,python-2.7,dictionary,Python,Python 2.7,Dictionary,我有这两本字典 Dict1 = {1: ('John', 37), 2: ('Tom', 23), 3: ('Tom', 19), 4: ('Jane', 58)} Dict2 = {1: ('2',), 2: ('4',), 3: ('19',)} 处理上述两个字典的输出字典为: OutputDict = {1: ('John', 37), 2: ('Tom', 23)} 获取OutputDict的逻辑如下 (1) Dict1和Dict2必须具有匹配的键。否则,OutputDict
Dict1 = {1: ('John', 37), 2: ('Tom', 23), 3: ('Tom', 19), 4: ('Jane', 58)}
Dict2 = {1: ('2',), 2: ('4',), 3: ('19',)}
处理上述两个字典的输出字典为:
OutputDict = {1: ('John', 37), 2: ('Tom', 23)}
获取OutputDict
的逻辑如下
(1) Dict1
和Dict2
必须具有匹配的键。否则,OutputDict
将丢弃Dict1
中的key:value对。
(2) 如果找到匹配的键,则Dict1
值中的第二个元素必须与Dict2
中的值不同。如果它们相同,OutputDict
将丢弃Dict1
中的key:value对
如何用Python编程?我正在使用Python 2.7。这就是您想要的吗
Dict1 = {1: ('John', 37), 2: ('Tom', 23), 3: ('Tom', 19), 4: ('Jane', 58)}
Dict2 = {1: ('2',), 2: ('4',), 3: ('19',)}
OutputDict = {k: v for (k, v) in Dict1.iteritems() if k in Dict2 and v[1] != int(Dict2[k][0])}
print OutputDict
输出:
{1: ('John', 37), 2: ('Tom', 23)}
{1: ('John', 37), 2: ('Tom', 23)}
您可以使用来迭代Dict1
中的键值对,仅保留这些键值对,以便(1)键位于Dict2
中;和(2)数值匹配Dict1
和Dict2
:
演示
>>> OutputDict = { k: v for k, v in Dict1.iteritems()
if k in Dict2 and int(Dict2[k][0]) != v[1] }
>>> OutputDict
{1: ('John', 37), 2: ('Tom', 23)}
使用zip:
outDict = {i:Dict1[i] for i,j in zip(Dict1.keys(),Dict2.keys()) if i==j and int(Dict1[i][1]) != int(Dict2[i][0])}
输出:
{1: ('John', 37), 2: ('Tom', 23)}
{1: ('John', 37), 2: ('Tom', 23)}
到目前为止你试过什么?您在制定解决方案时是否遇到了具体的概念性问题?我想知道是否应该使用for循环,或者是否有一种更具python风格的方法来解决此问题。@user3293156在您真正熟悉列表/Dict理解之前,请始终从for循环开始,然后确定逻辑是否足够简单,可以放入某种理解。对于更复杂的理解,我仍然会首先写出For循环,这样我就有了一个可以比较的输出。+1:我更喜欢这一个,而不是另一个dict理解答案,主要是因为提出问题的人显然比python新,这实际上给出了一些解释,而不仅仅是“答案”谢谢你的解释。我绝对需要它。然而,我从堆栈溢出专家那里得到答案的惊人速度令人沮丧。这么快,直到我认为我不适合做一名程序员。你们怎么配?唉。