你如何在Python中创建嵌套的字典?(How do you create nested dict

2019-09-01 17:05发布

我有2个的CSV文件。 第一个是一个数据文件,而另一个是一个映射文件。 映射文件中有4列: Device_NameGDNDevice_TypeDevice_OS 。 同列数据中存在的文件。

数据文件包含与数据Device_Name填充柱与其他三列空白。 所有四列被填充在映射文件。 我希望我的Python代码来打开这两个文件并为每个Device_Name在数据文件中,映射其GDNDevice_TypeDevice_OS从映射文件中值。

我知道如何使用字典的时候只有2列存在(需要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)

它返回的Atribute Error

一些经过研究,我意识到,我需要创建一个嵌套的字典,但我没有对如何做到这一点的想法。 请帮我解决这个或轻移我在正确的方向来解决这个问题。

Answer 1:

嵌套字典是一个字典内的字典。 一个非常简单的事情。

>>> d = {}
>>> d['dict1'] = {}
>>> d['dict1']['innerkey'] = 'value'
>>> d
{'dict1': {'innerkey': 'value'}}

你也可以使用一个defaultdictcollections包,方便创建嵌套的字典。

>>> import collections
>>> d = collections.defaultdict(dict)
>>> d['dict1']['innerkey'] = 'value'
>>> d  # currently a defaultdict type
defaultdict(<type 'dict'>, {'dict1': {'innerkey': 'value'}})
>>> dict(d)  # but is exactly like a normal dictionary.
{'dict1': {'innerkey': 'value'}}

您可以填充该不过你想要的。

我建议在你的代码类似如下:

d = {}  # can use defaultdict(dict) instead

for row in file_map:
    # derive row key from something 
    # when using defaultdict, we can skip the next step creating a dictionary on row_key
    d[row_key] = {} 
    for idx, col in enumerate(row):
        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到a.csv文件键列映射JK L列的值

我的建议是这样的(不使用defaultdict):

a_file = "path/to/a.csv"
b_file = "path/to/b.csv"

# read from file a.csv
with open(a_file) as f:
    # skip headers
    f.next()
    # get first colum as keys
    keys = (line.split(',')[0] for line in f) 

# create empty dictionary:
d = {}

# read from file b.csv
with open(b_file) as f:
    # gather headers except first key header
    headers = f.next().split(',')[1:]
    # iterate lines
    for line in f:
        # gather the colums
        cols = line.strip().split(',')
        # check to make sure this key should be mapped.
        if cols[0] not in keys:
            continue
        # add key to dict
        d[cols[0]] = dict(
            # inner keys are the header names, values are columns
            (headers[idx], v) for idx, v in enumerate(cols[1:]))

请注意:虽然,用于解析CSV文件中有一个CSV模块 。



Answer 2:

更新 :对于嵌套字典的任意长度,去这个答案 。

从集合使用defaultdict功能。

高性能:“如果key不在字典”是当数据集很大很贵。

低维护:使代码更易读,可以很容易地扩展。

from collections import defaultdict

target_dict = defaultdict(dict)
target_dict[key1][key2] = val


Answer 3:

对于嵌套结构的任意级别:

In [2]: def nested_dict():
   ...:     return collections.defaultdict(nested_dict)
   ...:

In [3]: a = nested_dict()

In [4]: a
Out[4]: defaultdict(<function __main__.nested_dict>, {})

In [5]: a['a']['b']['c'] = 1

In [6]: a
Out[6]:
defaultdict(<function __main__.nested_dict>,
            {'a': defaultdict(<function __main__.nested_dict>,
                         {'b': defaultdict(<function __main__.nested_dict>,
                                      {'c': 1})})})


Answer 4:

它采用defaultdict和类似嵌套的字典模块,如nested_dict时,即寻找一个不存在的关键可能在无意中创造的字典一个新的关键条目,并造成大量破坏的记忆是很重要的。 这里是一个Python3例如与nested_dict。

import nested_dict as nd
nest = nd.nested_dict()
nest['outer1']['inner1'] = 'v11'
nest['outer1']['inner2'] = 'v12'
print('original nested dict: \n', nest)
try:
    nest['outer1']['wrong_key1']
except KeyError as e:
    print('exception missing key', e)
print('nested dict after lookup with missing key.  no exception raised:\n', nest)

# instead convert back to normal dict
nest_d = nest.to_dict(nest)
try:
    print('converted to normal dict. Trying to lookup Wrong_key2')
    nest_d['outer1']['wrong_key2']
except KeyError as e:
    print('exception missing key', e)
else:
    print(' no exception raised:\n')
# or use dict.keys to check if key in nested dict.
print('checking with dict.keys')
print(list(nest['outer1'].keys()))
if 'wrong_key3' in list(nest.keys()):

    print('found wrong_key3')
else:
    print(' did not find wrong_key3')

输出是:

original nested dict:   {"outer1": {"inner2": "v12", "inner1": "v11"}}

nested dict after lookup with missing key.  no exception raised:  
{"outer1": {"wrong_key1": {}, "inner2": "v12", "inner1": "v11"}} 

converted to normal dict. 
Trying to lookup Wrong_key2 

exception missing key 'wrong_key2' 

checking with dict.keys 

['wrong_key1', 'inner2', 'inner1']  
did not find wrong_key3


文章来源: How do you create nested dict in Python?