Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple list from dict in Python [duplicate]

How can I obtain a list of key-value tuples from a dict in Python?

like image 540
Manuel Araoz Avatar asked Aug 18 '09 19:08

Manuel Araoz


People also ask

Does tuple take duplicates in Python?

Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

How do you find duplicates in tuple Python?

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() .

Does Dict allow duplicates in Python?

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.


2 Answers

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()) 
like image 121
Andrew Keeton Avatar answered Oct 04 '22 14:10

Andrew Keeton


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 
like image 31
Kenan Banks Avatar answered Oct 04 '22 15:10

Kenan Banks