Pythonでネストされた辞書を作成するにはどうすればいいですか? 質問する

Pythonでネストされた辞書を作成するにはどうすればいいですか? 質問する

2 つの CSV ファイルがあります: 「データ」と「マッピング」:

  • 「マッピング」ファイルには、、、、の 4 つの列があります。4つDevice_Nameの列すべてにデータが入力されています。GDNDevice_TypeDevice_OS
  • 「データ」ファイルにはこれらの同じ列があり、Device_Name列が入力され、他の 3 つの列は空白になっています。
  • Python コードで両方のファイルを開き、Device_Nameデータ ファイル内のそれぞれのGDNDevice_Type、 のDevice_OS値をマッピング ファイルからマップします。

2 つの列のみが存在する場合 (1 つをマップする必要がある) に dict を使用する方法はわかっていますが、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

いくつか調べた結果、ネストされた辞書を作成する必要があると思うのですが、その方法がわかりません。

ベストアンサー1

ネストされた辞書は辞書内の辞書です。非常に単純なものです。

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

また、defaultdictからcollectionsネストされた辞書の作成を容易にするパッケージ。

>>> 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 はこれらの csv のキー列のようなものです。jkl 列は a.csv では空ですが、b.csv では入力されています。b.csv から a.csv ファイルに 'i` をキー列として使用して jkl 列の値をマップしたいです。

私の提案はのようにこれは(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モジュール

おすすめ記事