I have got tuples nested in a list.
Every tuple have 3 objects inside them.
And i have created a dictionary for the first and second object in the list and a dictionary for the first and third object in the list.
My main Problem is that I can not get the values inside the tuples in the list.
I tried a List Comprehension, Which only works for list.
I needed a way to insert the objects to the dictionary.
Variable = [('Bla','Blo','foo'),('Hello','Bye','Seeyou'),('Morning','Afternoon','Evening')]
Dictionary1 = {}
Dictionary2 = {}
for item in Variable:
PreKidsVar[x[len(PreKidsVar)]
This is how I expected it:
Dictionary1 = {'Bla':'Blo','Hello':'Bye','Morning':'Afternoon'}
Dictionary2 = {'Bla':'foo','Hello':'Seeyou','Morning':'Evening'}
You can use dict-comprehension
as below:
Dictionary1 = {i[0]:i[1] for i in Variable}
Dictionary2 = {i[0]:i[2] for i in Variable}
Or you can do:
Dictionary1 = {}
Dictionary2 = {}
for i in Variable:
Dictionary1[i[0]] = i[1]
Dictionary2[i[0]] = i[2]
print(Dictionary1)
print(Dictionary2)
You can use below code which uses single for loop:
Variable = [('Bla','Blo','foo'),('Hello','Bye','Seeyou'),('Morning','Afternoon','Evening')]
dict1 ={}
dict2 ={}
for i in Variable:
dict1[i[0]]=i[1]
dict2[i[0]]=i[2]
print(dict1)
print(dict2)
Result:
{'Bla': 'Blo', 'Hello': 'Bye', 'Morning': 'Afternoon'}
{'Bla': 'foo', 'Hello': 'Seeyou', 'Morning': 'Evening'}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.