0

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.

2
  • are those really list of dictionaries??? Commented Sep 17, 2020 at 7:11
  • Sorry, I realized I made a mistake when typing the simplified example. It should read [{stuff},{stuff}] and there should be brackets around the numbers to denote a list of what I want to get: num: ['10','3','5','1']. edited Is that better? I can post the actual code but it's lengthy. Commented Sep 17, 2020 at 7:13

2 Answers 2

1

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']}]
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Thank you for the clarification! I am new to Python and still not used to the syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.