Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Convert value in dictionaries from a list of dictionaries from a string to integer

I have a list of dictionaries, where the key and values are both strings. However, I want to convert the value from a string to a int.

I have tried multiple ways but nothing seems to be working, either I receive 'key error: '1' or 'size of dictionary has changed'.

My dictionary looks like this (I have total 54 dictionaries)

{'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 so on.

My code:

import csv
import pprint
from typing import List, Dict

input_file_1 = csv.DictReader(open("DATA CWK SHOPPING DATA WEEK 1 FILE B.xlsb.csv"))

table = list(input_file_1)

buyers = []
for row in table:
    buyers_list = {}
    for i in row:
        if row[i] != '' and i != 'PRODUCT NAME':
            buyers_list.update({i : row[i]})
    buyers.append(buyers_list)

pprint.pprint(buyers)
question from:https://stackoverflow.com/questions/65943955/convert-value-in-dictionaries-from-a-list-of-dictionaries-from-a-string-to-integ

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

1 Reply

0 votes
by (71.8m points)
my_list = [{'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'}]

for k in my_list:
    for t in k.keys():
        k[t] = int(k[t])

This program will do your work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...