Convert tuple to dictionary python

For the tuple, t = [[1, 'a'],[2, 'b']] dict[t] returns {1: 'a', 2: 'b'}

Is there a good way to get {'a': 1, 'b': 2} [keys and vals swapped]?

Ultimately, I want to be able to return 1 given 'a' or 2 given 'b', perhaps converting to a dict is not the best way.

asked Sep 24, 2010 at 1:04

JakeJake

12.2k16 gold badges61 silver badges95 bronze badges

Try:

>>> t = [[1, 'a'],[2, 'b']]
>>> dict[[y, x] for x, y in t]
{'a': 1, 'b': 2}

answered Sep 24, 2010 at 1:07

Greg HewgillGreg Hewgill

909k177 gold badges1131 silver badges1267 bronze badges

4

A slightly simpler method:

>>> t = [[1, 'a'],[2, 'b']]
>>> dict[map[reversed, t]]
{'a': 1, 'b': 2}

answered Oct 5, 2011 at 20:46

jterracejterrace

62.2k22 gold badges153 silver badges195 bronze badges

4

Even more concise if you are on python 2.7:

>>> t = [[1,'a'],[2,'b']]
>>> {y:x for x,y in t}
{'a':1, 'b':2}

answered Mar 2, 2013 at 21:20

autholykosautholykos

7967 silver badges14 bronze badges

>>> dict[[['hi','goodbye']]]
{'hi': 'goodbye'}

Or:

>>> [ dict[[i]] for i in [['CSCO', 21.14], ['CSCO', 21.14], ['CSCO', 21.14], ['CSCO', 21.14]] ]
[{'CSCO': 21.14}, {'CSCO': 21.14}, {'CSCO': 21.14}, {'CSCO': 21.14}]

Smi

13.4k9 gold badges55 silver badges63 bronze badges

answered Feb 14, 2013 at 0:05

GunnarssonGunnarsson

4905 silver badges5 bronze badges

0

If there are multiple values for the same key, the following code will append those values to a list corresponding to their key,

d = dict[]
for x,y in t:
    if[d.has_key[y]]:
        d[y].append[x]
    else:
        d[y] = [x]

answered Apr 10, 2016 at 1:15

psunpsun

5659 silver badges13 bronze badges

Here are couple ways of doing it:

>>> t = [[1, 'a'], [2, 'b']]

>>> # using reversed function
>>> dict[reversed[i] for i in t]
{'a': 1, 'b': 2}

>>> # using slice operator
>>> dict[i[::-1] for i in t]
{'a': 1, 'b': 2}

answered Jan 2, 2018 at 14:26

Vlad BezdenVlad Bezden

75.9k23 gold badges236 silver badges175 bronze badges

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]}

Input : [["Nakul",93], ["Shivansh",45], ["Samved",65],
             ["Yash",88], ["Vidit",70], ["Pradeep",52]]
Output : {'Nakul': [93], 'Shivansh': [45], 'Samved': [65], 
            'Yash': [88], 'Vidit': [70], 'Pradeep': [52]}

Input : [['Sachin', 10], ['MSD', 7], ['Kohli', 18], ['Rohit', 45]]
Output : {'Sachin': 10, 'MSD': 7, 'Kohli': 18, 'Rohit': 45}

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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.

Example 1:

def Convert[tup, di]:

    for a, b in tup:

        di.setdefault[a, []].append[b]

    return di

tups = [["akash", 10], ["gaurav", 12], ["anand", 14], 

     ["suraj", 20], ["akhil", 25], ["ashish", 30]]

dictionary = {}

print [Convert[tups, dictionary]]

Output:

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

Example 2:

list_1=[["Nakul",93], ["Shivansh",45], ["Samved",65],

           ["Yash",88], ["Vidit",70], ["Pradeep",52]]

dict_1=dict[]

for student,score in list_1:

    dict_1.setdefault[student, []].append[score]

print[dict_1]

Output:

{'Nakul': [93], 'Shivansh': [45], 'Samved': [65], 'Yash': [88], 'Vidit': [70], 'Pradeep': [52]}

Method 2 : Use of dict[] method

Example 1:

def Convert[tup, di]:

    di = dict[tup]

    return di

tups = [["akash", 10], ["gaurav", 12], ["anand", 14], 

    ["suraj", 20], ["akhil", 25], ["ashish", 30]]

dictionary = {}

print [Convert[tups, dictionary]]

Output:

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

Example 2:

print [dict[[['Sachin', 10], ['MSD', 7], ['Kohli', 18], ['Rohit', 45]]]]

Output:

{'Sachin': 10, 'MSD': 7, 'Kohli': 18, 'Rohit': 45}

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.


Can I put a tuple in a dictionary?

Because tuples are hashable and lists are not, if we want to create a composite key to use in a dictionary we must use a tuple as the key. Write code to create a dictionary called 'd1', and in it give the tuple [1, 'a'] a value of “tuple”.

How do you create a dictionary from a list of tuples?

Converting a list of tuples into a dictionary is a straightforward thing..
Initialize the list with tuples..
Use the dict to convert given list of tuples into a dictionary..
Print the resultant dictionary..

Can tuple be dictionary Python?

Answer. Yes, a tuple is a hashable value and can be used as a dictionary key.

Which of the following function convert a sequence of tuples to dictionary in Python?

Type Conversion.

Chủ Đề