Here is an extract from one of my python functions:
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
d_list = []
for key,value in d.iteritems():
temp = [key, value]
d_list.append(temp)
When I print d_list
it currently gives me:
>>>print d_list
[['ANIMAL', ['CAT', 'DOG', 'FISH', 'HEDGEHOG']]]
How do I rewrite the function so it gives me:
>>>print d_list
[['ANIMAL', 'CAT'],['ANIMAL', 'DOG'],['ANIMAL', 'FISH'],['ANIMAL', 'HEDGEHOG']]
Two nested loops can do this easily -
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
d_list = []
for key, values in d.iteritems():
for value in values:
d_list.append([key, value])
Using list comprehension -
d_list = [[k,v] for k, values in d.iteritems() for v in values]
For python 3.x, you should change iteritems
to items
This is how I would do it. I would iterate over the value's of the key directly.
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
d_list = []
for value in d['ANIMAL']:
temp = ['ANIMAL',value]
d_list.append(temp)
print (d_list)
Result:
[['ANIMAL', 'CAT'], ['ANIMAL', 'DOG'], ['ANIMAL', 'FISH'], ['ANIMAL', 'HEDGEHOG']]
You need a second loop:
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
d_list = []
for key, values in d.iteritems():
for value in values:
temp_list=[key, value]
d_list.append(temp)
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.