Fus*_*dev 2 python dictionary list python-3.x
我有以下词典
dic1 = { 'T1': "HI , china" , 'T2': "HI , finland" ,'T3': "HI , germany"}
dic2 = { 'T1': ['INC1','INC2','INC3'] , 'T2': ['INC2','INC4','INC5'],'T3': ['INC2','INC5']}
dic3 = { 'INC1': {'location':'china'} , 'INC2': {'location':'germany'},'INC3': {'location':'germany'},'INC4': {'location':'finland'}}
Run Code Online (Sandbox Code Playgroud)
我需要根据 dic1,dic3 删除 dic2 中的值
例子 :
图片中给出了详细的解释。我期待以下输出。
dic2 = { 'T1': ['INC1'] , 'T2': ['INC4'],'T3': ['INC2']}
Run Code Online (Sandbox Code Playgroud)
示例代码:
for k, v in dic2.items():
for k1, v1 in dic1.items():
if k is k1:
print k
for k2 in v:
for k3 in dic3.items():
Run Code Online (Sandbox Code Playgroud)
我是python的新手。我已经尝试了上面的代码片段,但我被打倒了。你能帮帮我吗?
可以在单行中完成:
>>> {k: [i for i in v if dic3.get(i, {}).get('location', '#') in dic1[k]] for k, v in dic2.items()}
{'T1': ['INC1'], 'T2': ['INC4'], 'T3': ['INC2']}
Run Code Online (Sandbox Code Playgroud)
[i for i in v if dic3.get(i, {}).get('location', '#')
在列表理解从挑只值dic2
,如果的名单dic3[i]['location']
里面dic1[k]
,这里i
是在字典的关键d3
,并k
从字典的关键d2
,以及字典d1
。
我使用dic3.get(i, {}).get('location', '#')
(而不是dic3[i]['location']
,你得到KeyError
了INC5
不在的键dic3
)以避免键i
不在的问题dic3
(将为dict
我的下一个返回一个空.get
),在第二个中.get
,我再次使用它来返回location
键的相应值,如果它存在并检查返回的字符串是否位于 dict 的值内d1
。
我返回#
(可以是任何字符串/字符),如果我知道该键i
不存在于dic3
(i
不存在本质上{}.get('location', '#')
会给出#
,反过来会给出,这肯定会使 中的成员资格失败d1
,因此没关系)。
淡化 for 循环版本:
>>> ans = {}
>>> for k, v in dic2.items():
... temp = []
... for i in v:
... if i in dic3 and dic3[i]['location'] in dic1[k]:
... temp.append(i)
... ans[k] = temp
...
>>> ans
{'T1': ['INC1'], 'T2': ['INC4'], 'T3': ['INC2']}
Run Code Online (Sandbox Code Playgroud)