我知道这个问题已被问到,但我找不到任何将值附加到列表而不是创建列表列表的内容。我有两个具有相同值的词典:
dictionary1 = {'1':'one', '2':'two', '3':'three'}
dictionary2 = {'1':['uno'], '2':['dos'], '3':['tres']}
我需要它来回复:
combined = {'1':['one','uno'] '2':['two','dos'] '3':['three',tres']}
到目前为止,我尝试的所有内容都会返回:
combined = {'1':['one'['uno']] '2':['two'['dos']] '3':['three'[tres']]}
有嵌套列表。如何将字典1的值附加到dictionary2列表中?请帮助我,我知道这很简单,但我不知道该怎么做。谢谢
这是我的代码:
combined = {key:[dictionary1[key], dictionary2[key]] for key in dictionary1}
答案 0 :(得分:2)
实际上,您的代码已经正确了吗?
>>> dictionary1 = {'1':'one', '2':'two', '3':'three'}
>>> dictionary2 = {'1':'uno', '2':'dos', '3':'tres'}
>>> combined = {key:[dictionary1[key], dictionary2[key]] for key in dictionary1}
>>> combined
{'3': ['three', 'tres'], '2': ['two', 'dos'], '1': ['one', 'uno']}
除此之外你确定你没有做任何其他事吗?
答案 1 :(得分:1)
dictionary1 = {'1':'one', '2':'two', '3':'three'}
dictionary2 = {'1':['uno'], '2':['dos'], '3':['tres']}
combined = {key:[dictionary1[key], dictionary2[key][0]] for key in dictionary1}
只需从dictionary2
的值中检索第0个索引,考虑它们都是长度为1的列表。
否则,这将起作用:
combined = {key:[dictionary1[key]] + dictionary2[key] for key in dictionary1}
这基本上会在dictionary1
的值中创建一个元素列表,并将其与已列出的dictionary2
值组合在一起。
答案 2 :(得分:0)
dictionary1 = {'1':'one', '2':'two', '3':'three'}
dictionary2 = {'1':'uno', '2':'dos', '3':'tres'}
z = zip(zip(dictionary1.keys(), dictionary2.keys()),
zip(dictionary1.values(), dictionary2.values()))
dual = {}
for el in z:
dual[el[0][0]] = el[1]
print(list(dual.items()))
<强> OUPUT 强>
[(&#39; 2&#39;,(&#39; 2&#39;,#39; dos&#39;)),(&#39; 1&#39;,(&#39;一个&#39;,&#39; uno&#39;),(&#39; 3&#39;,(&#39;三&#39;,&#39; tres&#39;))]