我有這個嵌套字典:
Movies = {1: {'1060277': 'cloverfield', '1877830': 'The Batman', '0117283': 'The Pallbearer'},
2: {'1877830': 'The Batman', '1877321': 'The Yards', '0117283': 'The Pallbearer'},
3: {'6723592': 'Tenet', '1099212': 'Twilight', '1877830': 'The Batman'}}
現在,我想回傳一個字典,其中包含嵌套字典中所有字典的公共鍵值對,在本例中為
--> 1877830 The Batman
因為它是所有 3 個嵌套字典共有的唯一一個。
我似乎無法弄清楚如何比較這些字典:
#mov is where Movies will be passed
def Narrow_down(mov):
final_list= mov[1]
for i in final_list.keys():
for x,y in mov.items():
for key in y:
if i==key:
print(i, "is common ")
uj5u.com熱心網友回復:
你基本上想拿第一本字典,然后對于每一個下一個字典,只保留第一個字典中的鍵,這些鍵也在下一個字典中。
一個非常簡單的解決方案使用functools.reduce():
from functools import reduce
# you don't really need the outer dictionary, but if you do, this is list(Movies.values())
movies = [
{'1060277': 'cloverfield', '1877830': 'The Batman', '0117283': 'The Pallbearer'},
{'1877830': 'The Batman', '1877321': 'The Yards', '0117283': 'The Pallbearer'},
{'6723592': 'Tenet', '1099212': 'Twilight', '1877830': 'The Batman'}
]
result = reduce(lambda d1, d2: {k: v for k, v in d1.items() if k in d2 and d2[k] == d1[k]}, movies)
print(result)
結果:
{'1877830': 'The Batman'}
請注意,我命名了變數movies- 您應該避免使用大寫字母命名變數,因為這會導致其他人(也許未來的您)認為它是一個類名。
uj5u.com熱心網友回復:
您可以迭代外部字典的值,維護一組迄今為止看到的所有字典共有的鍵值對(使用集合交集操作)。然后,您可以使用字典理解將這組鍵值對轉換為字典:
common_items = None
for inner_dict in Movies.values():
if common_items is None:
common_items = set(inner_dict.items())
else:
common_items = common_items.intersection(inner_dict.items())
result = {key: value for key, value in common_items}
print(result)
對于給定的電影,這將列印:
{'1877830': 'The Batman'}
uj5u.com熱心網友回復:
您可以使用字典專案的集合交集:
set.intersection(*(set(d.items()) for d in Movies.values()))
輸出:{('1877830', 'The Batman')}
作為字典:
dict(set.intersection(*(set(d.items()) for d in Movies.values())))
輸出:{'1877830': 'The Batman'}
uj5u.com熱心網友回復:
如果您真的只想要公共鍵值對,那么這里的代碼會洗掉具有相同鍵但該鍵值不同的鍵值對:
common_keys: set = None
for _, nested_dict in Movies.items():
if common_keys is None:
common_keys = set(nested_dict.keys())
else:
common_keys = common_keys.intersection(set(nested_dict.keys()))
# remove key-value pairs with same keys but different values
common_key_value_pairs = {}
common_keys_different_values = set()
for common_key in common_keys:
for _, nested_dict in Movies.items():
if common_key in common_key_value_pairs:
if common_key_value_pairs[common_key] != nested_dict[common_key]:
common_keys_different_values.add(common_key)
else:
common_key_value_pairs[common_key] = nested_dict[common_key]
for key in common_keys_different_values:
print(f"Key {key} has different values in the respective dicts")
del common_key_value_pairs[key]
print(common_key_value_pairs)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/449221.html
上一篇:Python將串列附加到字典中。串列被分成單獨的字符而不是整個
下一篇:從CSV檔案創建字典
