Python | Convert a list of Tuples into Dictionary

Sometimes you might need to convert a tuple to dict object to make it more readable.
In this article, we will try to learn how to convert a list of tuples into a dictionary. Here we will find two methods of doing this.
Examples:

Input : [("akash", 10), ("gaurav", 12), ("anand", 14), 
         ("suraj", 20), ("akhil", 25), ("ashish", 30)]
Output : {'akash': [10], 'gaurav': [12], 'anand': [14], 
          'ashish': [30], 'akhil': [25], 'suraj': [20]}

Input : [('A', 1), ('B', 2), ('C', 3)]
Output : {'B': [2], 'A': [1], 'C': [3]}

Method 1 : Use of setdefault()

Here we have used the dictionary method setdefault() to convert the first parameter to key and the second to the value of the dictionary. setdefault(key, def_value) function searches for a key and displays its value and creates a new key with def_value if the key is not present. Using the append function we just added the values to the dictionary.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to convert into dictionary
  
def Convert(tup, di):
    for a, b in tup:
        di.setdefault(a, []).append(b)
    return di
      
# Driver Code    
tups = [("akash", 10), ("gaurav", 12), ("anand", 14), 
     ("suraj", 20), ("akhil", 25), ("ashish", 30)]
dictionary = {}
print (Convert(tups, dictionary))

chevron_right


Output:

{'akash': [10], 'gaurav': [12], 'anand': [14], 
 'ashish': [30], 'akhil': [25], 'suraj': [20]}

Method 2 : Use of dict() method

This is a simple method of conversion from a list or tuple to a dictionary. Here we pass a tuple into the dict() method which converts the tuple into the corresponding dictionary.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to convert into dictionary
def Convert(tup, di):
    di = dict(tup)
    return di
      
# Driver Code 
tups = [("akash", 10), ("gaurav", 12), ("anand", 14), 
    ("suraj", 20), ("akhil", 25), ("ashish", 30)]
dictionary = {}
print (Convert(tups, dictionary))

chevron_right


Output:

{'anand': 14, 'akash': 10, 'akhil': 25, 
 'suraj': 20, 'ashish': 30, 'gaurav': 12}


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.