在Python中使用相同的键合并两个字典

我有两个字典与相同的键相同。 第字典是:在Python中使用相同的键合并两个字典

{ "key_1" : "AR" , 

"key_2":"BR" ,

"key_3" : "CR" }

第二个是:

{ "key_1" : "signinfication of AR" , 

"key_2":" signinfication of BR" ,

"key_3" : " signinfication of CR" }

,我希望获得下面的词典:

{"key_1" : {"AR" : "signinfication of AR"} , 

"key_2" : {"BR" : "signinfication of BR"} ,

"key_3" : {"CR" : "signinfication of CR"}

谢谢您的帮助!

回答:

这就像一条线一样简单字典理解

>>> {k : {d1[k] : d2[k]} for k in d1.keys() & d2.keys()} 

{

"key_2": {

"BR": " signinfication of BR"

},

"key_1": {

"AR": "signinfication of AR"

},

"key_3": {

"CR": " signinfication of CR"

}

}

这里,d1d2是你的两个库。 d1.keys() & d2.keys()将在字典键上执行交集,以确保对字典中存在的键进行迭代。在这里,这是

d1.keys() & d2.keys() 

{'key_1', 'key_2', 'key_3'}

这是很好的一般意义上,当你不能保证两个字典有完全相同的键。


python2.7及更高版本上,您需要稍作修改,因为keys()会返回一个列表。使用set.intersection -

>>> {k : {d1[k] : d2[k]} for k in set(d1.keys()).intersection(d2.keys())} 


如果你处理列表的类型的字典工作,那么上面的代码需要相应的列表之间的zip平 -

>>> d1 

{

"key_1": [

"AR",

"BR",

"CR"

],

...

}

>>> d2

{

"key_1": [

"signfication of AR",

"signfication of BR",

"signfication of CR"

],

...

}

>>> {k : dict(zip(d1[k], d2[k])) for k in d1.keys() & d2.keys()} 

{

"key_1": {

"BR": "signfication of BR",

"CR": "signfication of CR",

"AR": "signfication of AR"

},

"key_3": {

"CE": " signfication of CE",

"AE": "signfication of AE",

"BE": " signfication of BE"

},

"key_2": {

"BZ": "signfication of BZ",

"CZ": "signfication of CZ",

"AZ": "signfication of AZ"

}

}

回答:

你也可以zip()在一起的词典items(),并将它们合并在一起:

d1 = {"key_1" : "AR", 

"key_2":"BR",

"key_3" : "CR"}

d2 = {"key_1" : "signinfication of AR",

"key_2":" signinfication of BR",

"key_3" : " signinfication of CR"}

# make sure both lists have same ordered keys

l1 = sorted(d1.items())

l2 = sorted(d2.items())

d = {k1 : {v1:v2} for (k1, v1), (_, v2) in zip(l1, l2)}

print(d)

,输出:

{'key_1': {'AR': 'signinfication of AR'}, 

'key_2': {'BR': ' signinfication of BR'},

'key_3': {'CR': ' signinfication of CR'}}

编辑:

正如@cᴏʟᴅsᴘᴇᴇᴅ建议,你可以调用列表sorted荏苒他们,这确保了两个字典具有相同的顺序前:key_1key_2,key_3。您还可以对密钥进行初步检查,例如检查它们的交集,以确保两个字典具有相同的密钥。

回答:

你可以试试这个:

s = { "key_1" : "AR" , 

"key_2":"BR" ,

"key_3" : "CR" }

d = { "key_1" : "signinfication of AR" ,

"key_2":" signinfication of BR" ,

"key_3" : " signinfication of CR" }

new_d = {a:{b:d[a]} for a, b in s.items()}

输出:

{'key_1': {'AR': 'signinfication of AR'}, 'key_3': {'CR': ' signinfication of CR'}, 'key_2': {'BR': ' signinfication of BR'}} 

以上是 在Python中使用相同的键合并两个字典 的全部内容, 来源链接: utcz.com/qa/263700.html

回到顶部