如何在不导入模块的情况下将CSV文件读入嵌套字典

2024-05-14 21:11:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个CSV文件,我想读入词典词典,这样我就可以用['Aruba']['2020.05.22']['New_cas']索引词典,以便在某个日期访问阿鲁巴的新病例。就我个人而言,如果没有导入,怎么能做到这一点,因为网络上有很多这样的例子

这是CSV的一个片段:

iso,Con,Loc,Dat,Cas,New_cas
aaa,bbb,helsinki,2020.05.18,5,4
aaa,bbb,Aruba,2020.05.22,4,8
aaa,bbb,copenhagen,2020.07.19,8,
aaa,bbb,oslo,2020.02.03,10,19
aaa,bbb,oslo,2019.02.18,21,2
aaa,bbb,oslo,2019.02.18,,13

到目前为止,我的代码是:

dict= {} 
with open('filename.csv') as file:
    file.readline()  
    for line in file:
        iso,Con,Loc,Dat,Cas,New_cas = (s.strip('"') for s in line.split(','))
        if New_cas :
            if Loc not in dict:
                 dict[location] = [(New_cas ,Dat)]
            else:
                dict[location].append((New_cas ,Dat))
    

当前代码的输出形式

{'Aruba': [('2020-03-13', '2.0'), ('2020.05.22', '2.0'), ('2020-03-24', '8.0')..etc]}

预期产出:

print(covid_dict_3['helsinki']['2020.05.18']['New_cas'])
# 4 

Tags: csvinnewisoconoslolocdict
2条回答

您可以使用csv模块来解析文件:

import csv

data = {}
with open('filename.csv', 'r') as f_in:
    reader = csv.DictReader(f_in)
    for line in reader:
        loc = line.pop('Loc')
        dat = line.pop('Dat')
        data.setdefault(loc, {})[dat] = line

print(data['Aruba']['2020.05.22']['New_cas'])

印刷品:

8

data字典如下所示:

{'Aruba': {'2020.05.22': {'Cas': '4',
                          'Con': 'bbb',
                          'New_cas': '8',
                          'iso': 'aaa'}},
 'copenhagen': {'2020.07.19': {'Cas': '8',
                               'Con': 'bbb',
                               'New_cas': '',
                               'iso': 'aaa'}},
 'helsinki': {'2020.05.18': {'Cas': '5',
                             'Con': 'bbb',
                             'New_cas': '4',
                             'iso': 'aaa'}},
 'oslo': {'2019.02.18': {'Cas': '',
                         'Con': 'bbb',
                         'New_cas': '13',
                         'iso': 'aaa'},
          '2020.02.03': {'Cas': '10',
                         'Con': 'bbb',
                         'New_cas': '19',
                         'iso': 'aaa'}}}

编辑:不带标题的版本:

data = {}
with open('filename.csv', 'r') as f_in:
    header = [*map(str.strip, next(f_in).split(','))]
    for line in f_in:
        line = dict(zip(header, map(str.strip, line.split(','))))
        loc = line.pop('Loc')
        dat = line.pop('Dat')
        data.setdefault(loc, {})[dat] = line

print(data['Aruba']['2020.05.22']['New_cas'])

看看这个

my_dict= {}
with open('filename.csv') as file:
    file.readline()
    for line in file:
        iso,Con,Loc,Dat,Cas,New_cas = (s.strip('"') for s in line.split(','))
        New_cas = New_cas.strip("\n")
        New_cas = int(New_cas) if New_cas != '' else 0
        if Cas :
            if Loc not in my_dict:
                my_dict[Loc] = {Dat : { "New_cas" : New_cas }}
            else:
                if Dat not in my_dict[Loc]:
                    my_dict[Loc][Dat] = { "New_cas" : New_cas }
                else:
                    my_dict[Loc][Dat]["New_cas"] += New_cas

print(my_dict['helsinki']['2020.05.18']['New_cas'])

#prints : 4

# when you need to get any city/date, you first check a city exists or not in you data otherwise you would get keyError

if 'delhi' not in my_dict:
    print('No Case found against the city provided')
    exit()

if '2020.09.01' not in my_dict['helsinki']:
    print('No Case found against the date provided in helsinki')
    exit()

print(my_dict['helsinki']['2020.05.18']['New_cas'])

相关问题 更多 >

    热门问题