[英]How to generate all possible combinations in a dictionary in a dictionary
所以我在這樣的字典中有一個字典:
{'d': {'c': 3}, 'c': {'d': 3, 'b': 2}, 'b': {'c': 2, 'a': 1}, 'a': {'b': 1}}
我需要 python 代碼來給出 output :
("d","c")
("c","d")
("c","b")
("b","c")
("b","a")
("a","b")
我不知道如何做到這一點,並且接受任何幫助。
謝謝
您可以將列表理解與dict.items
一起使用:
dct = {'d': {'c': 3}, 'c': {'d': 3, 'b': 2}, 'b': {'c': 2, 'a': 1}, 'a': {'b': 1}}
output = [(key_1, key_2) for key_1, subdct in dct.items() for key_2 in subdct]
print(output) # [('d', 'c'), ('c', 'd'), ('c', 'b'), ('b', 'c'), ('b', 'a'), ('a', 'b')]
x = {'d': {'c': 3}, 'c': {'d': 3, 'b': 2}, 'b': {'c': 2, 'a': 1}, 'a': {'b': 1}}
for i in x.keys():
for j in x.get(i).keys():
print((i,j))
dict1 = {'d': {'c': 3}, 'c': {'d': 3, 'b': 2}, 'b': {'c': 2, 'a': 1}, 'a': {'b': 1}}
[(k1,k2) for k1 in dict1.keys() for k2 in dict1[k1].keys()]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.