Reputation: 311
For example I have a dictionary dict
my_dictionary= {'a': 20, 'c': 60, 'b': 10}
In this case I have 3 keys from the dictionary. I would like to make pairs and store them as tuples in a list. For the above case I would have this
[(a,b),(a,c),(b,c)]
Note: no repetition.
What would be the best way to go about it without any using any external modules.
Thank you for contribution.
Upvotes: 0
Views: 192
Reputation: 23508
>>> dd = {'a': 20, 'c': 60, 'b': 10}
>>> keys = [i for i in dd]
>>> [(keys[i],keys[j]) for i in range(len(keys)) for j in range(i+1,len(keys))]
[('a', 'c'), ('a', 'b'), ('c', 'b')]
>>>
and usually it's not a very good idea to call your variables using reserved words (like dict
)
Upvotes: 2
Reputation: 133554
>>> from itertools import combinations
>>> d = {'a': 20, 'c': 60, 'b': 10}
>>> list(combinations(d, r=2))
[('a', 'c'), ('a', 'b'), ('c', 'b')]
Upvotes: 7