+ 2

How can I convert a list of tuples to a dictionary in Python?

I want to convert a list of tuples in to a dictionary: [(a, b, c, d, e),...] to {c: {a: (d, b),...},...}. Thi should be a nested distionary with a tuple inside. Can anyone help me?

19th May 2021, 8:10 AM
Gašper Koželj
Gašper Koželj - avatar
5 Antworten
+ 5
If you have access to google.com try searching "How can I convert a list of tuples to a dictionary in Python?" you will get relevant answers! HAPPY SEARCHING!
20th May 2021, 4:58 AM
NEZ
NEZ - avatar
+ 3
I didn't quite understand your example, but I think this will be useful: t=("a","b","c") #your tuple d={} #empty dictionary for i in range(len(t)): d[i]=t[i] print(d) Output: {0: 'a', 1: 'b', 2: 'c'} Cheers.
19th May 2021, 9:11 AM
Isaac Fernandes
Isaac Fernandes - avatar
+ 1
I managed to do it. It only works for my specific case though. If anyone is interested: def nested_dict(list): main_dict = {} dict_for_third = {} third = [] for _, _, c, _, _ in list: third.append(c) third = set(third) for t in third: for tuple in list: if tuple[2] == t: (dict_for_third[tuple[0]] = (tuple[3], tuple[1])) main_dict[t] = dict_for_third dict_for_third = {} return main_dict
20th May 2021, 6:24 PM
Gašper Koželj
Gašper Koželj - avatar
0
To create dictionary you need to require key and values. So in tuple you have only one value. So you can assign default key from 0,1,..
21st May 2021, 4:46 AM
Hamza Malik
Hamza Malik - avatar
- 2
Don't know, have never seen a feasible reason to do so, You can learn about zip() or create your own function to do that.
19th May 2021, 9:08 AM
Slick
Slick - avatar