简体   繁体   中英

Create a dict from combinations in a list

I'm trying to create a dict from all possible pairs of elements in a list. This is what I've tried.

>>from itertools import combinations
>>l = ['a','b','c']
>>dict(combinations(l,2))
{'a': 'c', 'b': 'c'}

This is wrong, as there are 3 possible combinations. It's missing 'a': 'b' . When I list(combinations(l,2)) however, it gives me all possible combinations:

[('a', 'b'), ('a', 'c'), ('b', 'c')]

What's the problem here?

You can use defaultdict in order to create a mapping to a list of values:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for k, *v in combinations(l, 2):
...     d[k].extend(v)
... 
>>> dict(d)
{'a': ['b', 'c'], 'b': ['c']}

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