简体   繁体   中英

How to generate all possible combinations in a dictionary in a dictionary

So I have a dict in a dict like so:

{'d': {'c': 3}, 'c': {'d': 3, 'b': 2}, 'b': {'c': 2, 'a': 1}, 'a': {'b': 1}}

And I need python code to give an output of:

("d","c")
("c","d")
("c","b")
("b","c")
("b","a")
("a","b")

I have no clue how to do this and any help is accepted.

Thank you

You can use list comprehension with 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()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM