+ 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?
5 Respuestas
+ 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!
+ 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.
+ 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
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,..
- 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.