我正在尝试从 CSV 中将每个值读入 python 字典。我究竟做错了什么?
I am trying to read every value into a python dictionary from the CSV. What am I doing wrong?
我正在尝试在 DynamoDB(亚马逊网络服务)中使用 batch_writer()。
您的代码嵌套不正确。下面是一些示例代码,首先将语言文件读入字典,然后遍历区域文件:
languages = {}
table = []
# Load languages, catering for multiple languages
with open('shortlist_languages.csv') as languages_file:
for line in languages_file:
fields = line.strip().split(',')
languages[fields[0]] = ','.join(fields[2:])
# Load countries
with open('shortlist_area.csv') as countries_file:
for line in countries_file:
fields = line.strip().split(',')
table.append(
{
'Country Name': fields[1],
'Languages': languages[fields[0]],
'ISO3': fields[0],
'Area': fields[2]
}
)
print(table)
(我懒得用CSV函数了!)
输出为:
[
{
"Country Name": "Country Name",
"Languages": "Languages",
"ISO3": "ISO3",
"Area": "Area"
},
{
"Country Name": "Albania",
"Languages": "Albanian",
"ISO3": "ALB",
"Area": "28748"
},
{
"Country Name": "Algeria",
"Languages": "Arabic,Tamazight",
"ISO3": "DZA",
"Area": "2381741"
},
{
"Country Name": "Andorra",
"Languages": "Catalan",
"ISO3": "AND",
"Area": "468"
},
{
"Country Name": "Angola",
"Languages": "Portuguese",
"ISO3": "AGO",
"Area": "1246700"
}
]
请注意,阿尔及利亚的输出中包含多种语言。
我正在尝试在 DynamoDB(亚马逊网络服务)中使用 batch_writer()。
您的代码嵌套不正确。下面是一些示例代码,首先将语言文件读入字典,然后遍历区域文件:
languages = {}
table = []
# Load languages, catering for multiple languages
with open('shortlist_languages.csv') as languages_file:
for line in languages_file:
fields = line.strip().split(',')
languages[fields[0]] = ','.join(fields[2:])
# Load countries
with open('shortlist_area.csv') as countries_file:
for line in countries_file:
fields = line.strip().split(',')
table.append(
{
'Country Name': fields[1],
'Languages': languages[fields[0]],
'ISO3': fields[0],
'Area': fields[2]
}
)
print(table)
(我懒得用CSV函数了!)
输出为:
[
{
"Country Name": "Country Name",
"Languages": "Languages",
"ISO3": "ISO3",
"Area": "Area"
},
{
"Country Name": "Albania",
"Languages": "Albanian",
"ISO3": "ALB",
"Area": "28748"
},
{
"Country Name": "Algeria",
"Languages": "Arabic,Tamazight",
"ISO3": "DZA",
"Area": "2381741"
},
{
"Country Name": "Andorra",
"Languages": "Catalan",
"ISO3": "AND",
"Area": "468"
},
{
"Country Name": "Angola",
"Languages": "Portuguese",
"ISO3": "AGO",
"Area": "1246700"
}
]
请注意,阿尔及利亚的输出中包含多种语言。