简体   繁体   中英

Convert string to list within list of dictionaries in python

I currently have a list of dictionaries like this:

[ {'id': 'ABBA', 'num': '10 3 5 1'}, {'id': 'ABAC', 'num': '4 5 6 20'}]

How can I change the value associated with the num key from a string to a list and iterate that over the list of dictionaries? Like this:

[ {'id': 'ABBA', 'num': ['10','3','5','1']}, {'id': 'ABAC', 'num': ['4', '5', '6' '20']}]

I know there are similar questions out there on how to loop through a list of dictionaries and changing a string to a list, but I can't seem to put all of these together.

I've tried:

for i in list_of_dictionaries:
    for id, num in i.items():
        for val in num:
            val = val.split()
            print(val)
print(list_of_dictionaries)

But I get [] for val and then the same unchanged list of dictionaries back.

Use this instead:

for i in list_of_dictionaries:
    val = i['num'].split()
    print(val)
    i['num'] = val
print(list_of_dictionaries)

By the way notice that string keys for dictionaries should be inside quotes.

As you can see updating the value of i['num'] when you are iterating over list_of_dictionaries with i variable, changes the main list. So you don't need to create a new list and append new items each time.

Please check the snippet

a=[ {'id': 'ABBA', 'num': '10 3 5 1'}, {'id': 'ABAC', 'num': '4 5 6 20'}]
for i in a:
    i['num']=i['num'].split(' ')
#[{'id': 'ABBA', 'num': ['10', '3', '5', '1']}, {'id': 'ABAC', 'num': ['4', '5', '6', '20']}]

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