如何在Python中创建嵌套字典?

我有2个CSV文件:“数据”和“映射”:


'映射'文件有4列:Device_Name,GDN,Device_Type,和Device_OS。填充所有四列。

“数据”文件具有这些相同的列,其中Device_Name填充了列,而其他三列为空白。

我希望我的Python代码来打开这两个文件并为每个Device_Name数据文件,它的映射GDN,Device_Type以及Device_OS从映射文件中值。

我知道只有2列存在时才需要使用dict(需要映射1列),但是当需要映射3列时我不知道如何实现。


以下是我尝试完成的映射的代码Device_Type:


x = dict([])

with open("Pricing Mapping_2013-04-22.csv", "rb") as in_file1:

    file_map = csv.reader(in_file1, delimiter=',')

    for row in file_map:

       typemap = [row[0],row[2]]

       x.append(typemap)


with open("Pricing_Updated_Cleaned.csv", "rb") as in_file2, open("Data Scraper_GDN.csv", "wb") as out_file:

    writer = csv.writer(out_file, delimiter=',')

    for row in csv.reader(in_file2, delimiter=','):

         try:

              row[27] = x[row[11]]

         except KeyError:

              row[27] = ""

         writer.writerow(row)

它返回Attribute Error。


经过研究,我认为我需要创建一个嵌套的字典,但我不知道如何执行此操作


慕森卡
浏览 867回答 3
3回答

斯蒂芬大帝

嵌套字典是字典中的字典。非常简单的事情。>>> d = {}>>> d['dict1'] = {}>>> d['dict1']['innerkey'] = 'value'>>> d{'dict1': {'innerkey': 'value'}}你也可以使用一个defaultdict从collections包装,以方便创建嵌套的字典。>>> import collections>>> d = collections.defaultdict(dict)>>> d['dict1']['innerkey'] = 'value'>>> d&nbsp; # currently a defaultdict typedefaultdict(<type 'dict'>, {'dict1': {'innerkey': 'value'}})>>> dict(d)&nbsp; # but is exactly like a normal dictionary.{'dict1': {'innerkey': 'value'}}您可以根据需要填充。我建议在你的代码的东西像下面:d = {}&nbsp; # can use defaultdict(dict) insteadfor row in file_map:&nbsp; &nbsp; # derive row key from something&nbsp;&nbsp; &nbsp; # when using defaultdict, we can skip the next step creating a dictionary on row_key&nbsp; &nbsp; d[row_key] = {}&nbsp;&nbsp; &nbsp; for idx, col in enumerate(row):&nbsp; &nbsp; &nbsp; &nbsp; d[row_key][idx] = col根据您的评论:可能上面的代码令人困惑。我的问题简而言之:我有2个文件a.csv b.csv,a.csv有4列ijkl,b.csv也有这些列。我是这些csv的关键列。jkl列在a.csv中为空,但在b.csv中填充。我想使用'i`作为键列将b.csv中的jk l列的值映射到a.csv文件我的建议是什么像这样(不使用defaultdict):a_file = "path/to/a.csv"b_file = "path/to/b.csv"# read from file a.csvwith open(a_file) as f:&nbsp; &nbsp; # skip headers&nbsp; &nbsp; f.next()&nbsp; &nbsp; # get first colum as keys&nbsp; &nbsp; keys = (line.split(',')[0] for line in f)&nbsp;# create empty dictionary:d = {}# read from file b.csvwith open(b_file) as f:&nbsp; &nbsp; # gather headers except first key header&nbsp; &nbsp; headers = f.next().split(',')[1:]&nbsp; &nbsp; # iterate lines&nbsp; &nbsp; for line in f:&nbsp; &nbsp; &nbsp; &nbsp; # gather the colums&nbsp; &nbsp; &nbsp; &nbsp; cols = line.strip().split(',')&nbsp; &nbsp; &nbsp; &nbsp; # check to make sure this key should be mapped.&nbsp; &nbsp; &nbsp; &nbsp; if cols[0] not in keys:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; # add key to dict&nbsp; &nbsp; &nbsp; &nbsp; d[cols[0]] = dict(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # inner keys are the header names, values are columns&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (headers[idx], v) for idx, v in enumerate(cols[1:]))但是请注意,用于解析csv文件的是csv模块。

HUH函数

对于嵌套字典的任意长度,请转到此答案。使用集合中的defaultdict函数。高性能:当数据集很大时,“ if key not in dict”非常昂贵。维护成本低:使代码更具可读性,并且可以轻松扩展。from collections import defaultdicttarget_dict = defaultdict(dict)target_dict[key1][key2] = val

烙印99

对于任意级别的嵌套:In [2]: def nested_dict():&nbsp; &nbsp;...:&nbsp; &nbsp; &nbsp;return collections.defaultdict(nested_dict)&nbsp; &nbsp;...:In [3]: a = nested_dict()In [4]: aOut[4]: defaultdict(<function __main__.nested_dict>, {})In [5]: a['a']['b']['c'] = 1In [6]: aOut[6]:defaultdict(<function __main__.nested_dict>,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {'a': defaultdict(<function __main__.nested_dict>,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{'b': defaultdict(<function __main__.nested_dict>,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {'c': 1})})})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python