[英]Create A Nested Dictionary with lists from CSV file
I have a CSV file ("import.csv") which has the following data where each value is a string我有一个 CSV 文件(“import.csv”),其中包含以下数据,其中每个值都是一个字符串
KID, C1, C2, C3
ID1, X1, "X2, X2.5", X3
ID2, "Y1, Y1.5", Y2, Y3
I want to create a nested dictionary using the data like so我想使用这样的数据创建一个嵌套字典
'KID' {
'ID1' {
'C1': 'X1',
'C2': ['X2', 'X2.5'],
'C3': 'X3',
},
'ID2' {
'C1': ['Y1', 'Y1.5'],
'C2': 'Y2',
'C3': 'Y3',
},
I have the following code我有以下代码
import csv
dict = {}
with open("import.csv", mode='r') as data_file:
data = csv.DictReader(data_file)
for row in data:
item = artists.get(row["artist"], dict())
item["C1"] = str(row["C1"])
item["C2"] = str(row["C2"])
item["C3"] = str(row["C3"])
dict[row["KID"]] = item
Instead, I am getting a dictionary of相反,我得到了一本字典
'KID' {
'ID1' {
'C1': 'X1',
'C2': 'X2, X2.5',
'C3': 'X3',
},
'ID2' {
'C1': 'Y1, Y1.5',
'C2': 'Y2',
'C3': 'Y3',
},
I am looping through the dictionary by finding keys in the dictionary by value, so the string/list issue is messing me up.我通过按值查找字典中的键来遍历字典,所以字符串/列表问题让我很困惑。 Is there a way to change my dictionary creation or do I have to change the way my CSV is set up?
有没有办法改变我的字典创建或者我必须改变我的 CSV 的设置方式?
Use a wrapper function to look to return list if multiple values are present and string otherwise如果存在多个值,则使用包装函数查找返回列表,否则使用字符串
def get_str_or_list(value):
return value.split(",") if "," in value else value
item["C1"] = get_str_or_list(str(row["C1"]))
item["C2"] = get_str_or_list(str(row["C2"]))
item["C3"] = get_str_or_list(str(row["C3"]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.