简体   繁体   中英

Trying to load to a list of lists from a list of dictionaries

I am trying to load from a list of dictionary items to a list of list in Python 2.7. The data currently looks like 20 lines of the following:

[{'professional:xp': '100', 'personal:power': 'fly', 'personal:hero': 'yes', 'custom:color': 'black', 'professional:name': 'batman'}, {'professional:xp': '86', 'personal:power': 'think', 'personal:hero': 'no', 'custom:color': 'grey', 'professional:name': 'gandalf'}, ...]

I want to do something like this:

[[100, 'fly', 'yes', 'black', 'batman'][86, 'think', 'no', 'grey', 'gandalf']...]

I tried a lot of different ways to loop but I cannot get a result.

i = -1
j = -1
scanList = []
joinList = [[]]

for item in scanList:
    i = i+1
    for k, v in item.iteritems():
        j= j+1
        joinList[i][j].append(v)

I get the idea of loading the list via the nested loop (upfront I don't know if my i and j is in right place but I can work on that). I just keep getting out of index errors and I don't know if I should be initialize the list of lists before?

Now's a good time to learn about list comprehensions . Note also that [dict].values() conveniently returns the list of values in a dictionary.

joinList = [d.values() for d in scanList]

Beware that in Python 3.x values() returns a view object , which must be explicitly converted to a list:

# Python 3.x version
joinList = [list(d.values()) for d in scanList]

You can get the values of a dictionary with the values function . Now you have to iterate over your dictionaries and call values on them:

[d.values() for d in scan_list]

you can use this code:

for item in scanList:
    list = []
    for key, value in item.iteritems():
        list.append(value)
    joinlist.append(list)
data=[{'professional:xp': '100', 'personal:power': 'fly', 'personal:hero': 'yes', 'custom:color': 'black', 'professional:name': 'batman'}, {'professional:xp': '86', 'personal:power': 'think', 'personal:hero': 'no', 'custom:color': 'grey', 'professional:name': 'gandalf'}]

new_data=[list(j.values()) for j in data]
print(new_data)

output

[['yes', 'black', 'batman', 'fly', '100'], ['no', 'grey', 'gandalf', 'think', '86']]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM