Reputation: 133
I have a dict that contains site location names and key codes i'm trying to pull the site location names (which are values) out of the dict and make a simple list.
I have this code which prints exactly what i want:
for s in mydict['mykey']:
print(s['site'])
site1
site2
site3
site4
but when i try to do something like this:
for s in mydict['mykey']:
mylist = list(s['site'])
or
for s in mydict['mykey']:
mylist2 = (s['site'])
i only get the last value:
mylist
['s', 'i', 't', 'e', '4']
mylist2
'site4'
Basically just looking to have the sites in a list, one per line
Upvotes: 0
Views: 53
Reputation: 16623
Use a list comprehension:
mylist = [s['site'] for s in mydict['mykey']]
This is the equivalent of:
mylist = []
for s in mydict['mykey']:
mylist.append(s['site'])
Upvotes: 1