![](/img/trans.png)
[英]Build a new dictionary from the keys of one dictionary and the values of another dictionary
[英]Return values from one dictionary by comparing keys from another dictionary
我有兩個字典,我想獲取第二個字典的第一個字典的值。 兩個字典具有相同的鍵,但順序不同。 例如:
dict1={'a':1,'b':1,'c':0,'d':0,'e':1,'f':0,'g':1}
這是第一本詞典。 第二本字典是:
dict2={'c':3,'b':2,'a':1,'d':1,'e':0,'g':0,'f':0}
我想獲取與第一個字典對應的值,但按照第二個字典的鍵順序。 所以輸出應該是這樣的:
dict3={'c':0,'b':1,'a':1,'d':0,'e':1,'g':1,'f':0}
有沒有辦法做到這一點?
如果你有 Python 3.7+ 你可以使用這個:
dict1={'a':1,'b':1,'c':0,'d':0,'e':1,'f':0,'g':1}
dict2={'c':3,'b':2,'a':1,'d':1,'e':0,'g':0,'f':0}
dict3 = {k: dict1[k] for k in dict2.keys()}
print(dict3)
> {'c': 0, 'b': 1, 'a': 1, 'd': 0, 'e': 1, 'g': 1, 'f': 0}
dict 對象的插入順序保留特性已被聲明為 Python 語言規范的官方部分。
這是你的意思嗎?
dict3 = {key:dict1[key] for key in dict2.keys()}
在 python 3.9 上試過。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.