Python 创建嵌套字典

Python 创建嵌套字典,python,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()

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

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']}}
所以我认为听写理解是最好的方法?我很难弄清楚如何将此内容写入词典理解。

您可以使用:

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'])}
您可以使用:

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'])}
假设您在示例中使用的密钥格式

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 }
假设您在示例中使用的密钥格式

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 }
您可以根据需要更改匹配函数


你可以根据自己的需要更改匹配函数。

为什么不将
x={}
移动到
for
循环之外?嗯,这能解决我的问题吗?让我查一查。哈-的确。。。非常感谢。但是出于好奇,有人能用dict理解来写这篇文章吗?为什么不把
x={}
移到
for
循环之外呢?嗯,这能解决我的问题吗?让我查一查。哈-的确。。。非常感谢。但出于好奇,有人能用dict理解来写这篇文章吗?我认为这是错误的,因为内部元组也应该是dict,比如
{'a':['email1','email2']}
我甚至没有意识到。感谢您的澄清。我认为这是错误的,因为内部元组也应该是dict,比如
{'a':['email1','email2']}
,我甚至没有意识到。谢谢你的澄清。如果你不介意的话,你能解释一下
dict((y,)
在这个例子中做了什么吗?在这种情况下,
y
是一个包含两个元素的元组,例如:
('a',['email1','email2'])
,所以你必须通过
[y]
(y,)用额外的括号将其括起来
表示法以转换为字典。zip不是太依赖于
b
项的顺序吗?如果你不介意的话,你能解释一下
dict((y,)
在这种情况下做了什么吗?在这种情况下,
y
是一个元组,包含两个元素,例如:
('a',['email1','email2'])
因此您必须通过
[y]
(y,)
符号将其用额外的括号括起来,以便转换为字典。邮政编码是否太依赖于
b
项的顺序?