Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

python - Convert values from list of dictionaries from string to integer

I have a list of 54 dictionaries, formatted as so:

[{'1A': '1',
'3E': '2',
'PRODUCT NUMBER': '1',
'Week': '1'}
,

{'1A': '1',
 '1B': '1',
 '1C': '1',
 '1D': '2',
 '1E': '2',
 '2C': '1',
 '3E': '2',
 'PRODUCT NUMBER': '2',
 'Week': '1'},...] and etc

I am trying to convert the values from strings to integers.

I have successfully managed to do this for my very last dictionary, but it doesnt seem to be working for the rest.

This is my code:

for i in buyers: #buyers is the list
    for n in buyers_dict: # the code works without this line the same, i cant figure out where to implement the 'n'
        for k, v in buyers_list.items():
            buyers_list[k] = int(v)
pprint.pprint(buyers)

Like I said, the 54th dictionary values are converted, but the rest are still strings

here is my excel file:

Week 1 of the excel

I've then condensed the dictionaries to just contain the key values pairs that have a value. Now I need to convert the values into integers.

question from:https://stackoverflow.com/questions/65945320/convert-values-from-list-of-dictionaries-from-string-to-integer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Assuming your data is in this schema:

buyers = [{...}, {...}, ...]

You need to loop through the list of dicts then work on those dicts in particular:

for d in buyers:
    for k, v in d.items():
        d[k] = int(v)

Or in comprehension form:

buyers = [{k: int(v) for k, v in d.items()} for d in buyers]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...