How can I obtain a list of key-value tuples from a dict in Python?
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
Initial approach that can be applied is that we can iterate on each tuple and check it's count in list using count() , if greater than one, we can add to list. To remove multiple additions, we can convert the result to set using set() .
As you can see in the Screenshot, the output displays the dictionary but it does not have duplicate keys in a dictionary because in Python dictionary does not allow duplicate keys. If you want to get all those values from a list and store them in the dictionary then you have to use the unique key with every value.
For Python 2.x only (thanks Alex):
yourdict = {} # ... items = yourdict.items()
See http://docs.python.org/library/stdtypes.html#dict.items for details.
For Python 3.x only (taken from Alex's answer):
yourdict = {} # ... items = list(yourdict.items())
For a list of of tuples:
my_dict.items()
If all you're doing is iterating over the items, however, it is often preferable to use dict.iteritems()
, which is more memory efficient because it returns only one item at a time, rather than all items at once:
for key,value in my_dict.iteritems(): #do stuff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With