创建嵌套字典

时间:2015-08-02 17:21:53

标签: python

假设我分别有一个列表和一个字典:

a=['a.pdf','b.pdf']

b = {'a':['email1', 'email2'], 'b':['email3']}

我希望最终结果看起来像这个使用循环的嵌套字典。

x={'a.pdf':{'a':['email1', 'email2']}, 'b.pdf':{'b':['email3']}}

我尝试使用这样的for循环:

for element in a:
    x={}
    for key, value in b.items()
       x[element]={}
       x[found][key]=value

 print(x)

这不起作用,因为dict x正在通过每次迭代重新分配新值,因此最终结果是:

 {'b.pdf':{'b':['email3']}}

所以我假设dict理解是要走的路?我很难搞清楚如何将其写入词典理解中。

4 个答案:

答案 0 :(得分:1)

您可以使用:

a=['a.pdf','b.pdf']
b = {'a':['email1', 'email2'], 'b':['email3']}
new_dict = {k:v for k,v in zip(a,b.items())}

结果:

print(new_dict)
{'a.pdf': ('a', ['email1', 'email2']), 'b.pdf': ('b', ['email3'])}

答案 1 :(得分:1)

>>> a = ['a.pdf','b.pdf']
>>> b = {'a':['email1', 'email2'], 'b':['email3']}
>>> c = {x: dict((y,)) for x, y in zip(a, b.items())}
>>> print c
{'a.pdf': {'a': ['email1', 'email2']}, 'b.pdf': {'b': ['email3']}}

答案 2 :(得分:1)

x = {top_key: {sub_key: b[sub_key] for sub_key in b if sub_key == top_key[0]} for top_key in a}

假设您在示例中使用的密钥格式。

答案 3 :(得分:1)

a = ['a.pdf','b.pdf','c.pdf']
b = {'a':['email1', 'email2'], 'b':['email3']}
def match(m):
    return m[0]
d = { e: {match(e): b[match(e)]} for e in a if match(e) in b }

您可以将匹配功能更改为您的要求。