183

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

  • “映射”文件有 4 列:Device_NameGDNDevice_TypeDevice_OS. 所有四列都已填充。
  • “数据”文件具有这些相同的列,已Device_Name填充列,其他三列为空白。
  • 我希望我的 Python 代码打开这两个文件,并为Device_Name数据文件中的每个文件,从映射文件中映射其GDNDevice_TypeDevice_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

经过一番研究,我想我需要创建一个嵌套的字典,但我不知道如何做到这一点。

4

9 回答 9

376

嵌套字典是字典中的字典。很简单的一件事。

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

您还可以使用包中的 adefaultdictcollections帮助创建嵌套字典。

>>> 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 也有这些列。i 是这些 csvs 的关键列。jkl 列在 a.csv 中为空,但在 b.csv 中填充。我想将 jk l 列的值使用“i”作为键列从 b.csv 映射到 a.csv 文件

我的建议是这样的(不使用 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 模块

于 2013-05-02T08:24:17.403 回答
71

更新:对于任意长度的嵌套字典,请转到此答案

使用集合中的 defaultdict 函数。

高性能:当数据集很大时,“if key not in dict”非常昂贵。

低维护:使代码更具可读性并且可以轻松扩展。

from collections import defaultdict

target_dict = defaultdict(dict)
target_dict[key1][key2] = val
于 2015-12-07T20:22:38.063 回答
31

对于任意级别的嵌套:

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})})})
于 2016-03-30T04:18:32.610 回答
4

重要的是要记住,在使用 defaultdict 和类似的嵌套 dict 模块nested_dict时,查找不存在的键可能会无意中在 dict 中创建新的键条目并造成大量破坏。

这是一个带有nested_dict模块的 Python3 示例:

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
于 2017-03-03T20:26:03.040 回答
2
pip install addict
from addict import Dict

mapping = Dict()
mapping.a.b.c.d.e = 2
print(mapping)  # {'a': {'b': {'c': {'d': {'e': 2}}}}}

参考:

  1. 简单的 GitHub
  2. 瘾君子 GitHub
于 2021-04-20T10:06:01.817 回答
0
#in jupyter
import sys
!conda install -c conda-forge --yes --prefix {sys.prefix} nested_dict 
import nested_dict as nd
d = nd.nested_dict()

'd' 现在可以用来存储嵌套的键值对。

于 2021-03-10T14:44:35.323 回答
0

如果你想创建一个给定路径列表(任意长度)的嵌套字典,并对路径末尾可能存在的项目执行函数,这个方便的小递归函数非常有用:

def ensure_path(data, path, default=None, default_func=lambda x: x):
    """
    Function:

    - Ensures a path exists within a nested dictionary

    Requires:

    - `data`:
        - Type: dict
        - What: A dictionary to check if the path exists
    - `path`:
        - Type: list of strs
        - What: The path to check

    Optional:

    - `default`:
        - Type: any
        - What: The default item to add to a path that does not yet exist
        - Default: None

    - `default_func`:
        - Type: function
        - What: A single input function that takes in the current path item (or default) and adjusts it
        - Default: `lambda x: x` # Returns the value in the dict or the default value if none was present
    """
    if len(path)>1:
        if path[0] not in data:
            data[path[0]]={}
        data[path[0]]=ensure_path(data=data[path[0]], path=path[1:], default=default, default_func=default_func)
    else:
        if path[0] not in data:
            data[path[0]]=default
        data[path[0]]=default_func(data[path[0]])
    return data

例子:

data={'a':{'b':1}}
ensure_path(data=data, path=['a','c'], default=[1])
print(data) #=> {'a':{'b':1, 'c':[1]}}
ensure_path(data=data, path=['a','c'], default=[1], default_func=lambda x:x+[2])
print(data) #=> {'a': {'b': 1, 'c': [1, 2]}}
于 2020-10-07T12:10:32.923 回答
0

这个东西是空的嵌套列表, ne 将从中将数据附加到空字典

ls = [['a','a1','a2','a3'],['b','b1','b2','b3'],['c','c1','c2','c3'], 
['d','d1','d2','d3']]

这意味着在 data_dict 中创建四个空字典

data_dict = {f'dict{i}':{} for i in range(4)}
for i in range(4):
    upd_dict = {'val' : ls[i][0], 'val1' : ls[i][1],'val2' : ls[i][2],'val3' : ls[i][3]}

    data_dict[f'dict{i}'].update(upd_dict)

print(data_dict)

输出

{'dict0':{'val':'a','val1':'a1','val2':'a2','val3':'a3'},'dict1':{'val':'b ','val1':'b1','val2':'b2','val3':'b3'},'dict2':{'val':'c','val1':'c1','val2 ':'c2','val3':'c3'},'dict3':{'val':'d','val1':'d1','val2':'d2','val3':'d3 '}}

于 2021-01-11T08:38:35.823 回答
0
travel_log = {
    "France" : {"cities_visited" : ["paris", "lille", "dijon"], "total_visits" : 10},
    "india" : {"cities_visited" : ["Mumbai", "delhi", "surat",], "total_visits" : 12}
}
于 2021-03-26T08:47:37.987 回答