简体   繁体   English

从 csv 创建嵌套字典

[英]Create nested dictionary from csv

I have some data in a csv that when opened looks like this:我在 csv 中有一些数据,打开时看起来像这样:

Example Data
['', 'Name', 'Phone', 'Address', 'City', 'Country', 'Email']
['1', 'Bob Myers', '410-504-5887', '12334 Hamilton Way', 'Toronto', 'Canada', 'bob@gmail.com']
['2', 'Carlton James', '455-323-8479', '1234 James Rd', 'New York', 'USA', 'carlton@example.com']
['3', 'Frank Wright', '744-521-9874', '567 Travis St', 'Boston', 'USA', 'fw4322@yahoo.com']

I want to create a nested dictionary where I take the integer in '' and use it as a key for each nested dictionary.我想创建一个嵌套字典,其中我在 '' 中取整数并将其用作每个嵌套字典的键。 I found a few similar questions and tried:我发现了一些类似的问题并尝试过:

import csv
f = csv.DictReader(open('data.csv'))

result = {}
for row in f:
    key = row.pop('')
    result[key] = row
print(result)

Which yielded something like:这产生了类似的东西:

{'1': {'Name': 'Bob Myers', 'Phone': '410-504-5887', 'Address': '12334 Hamilton Way', 'City': 'Toronto',
'Country': 'Canada', 'Email': 'bob@gmail.com'}...

What do I change in my code to get my data to look something like this (without pandas):我在我的代码中做了什么改变来让我的数据看起来像这样(没有熊猫):

my_dict = {{'Name': {1: 'Bob Myers', 2: 'Carlton James', 3: 'Frank Wright'}}, 
 {'Phone': {1: '410-504-5887', 2: '455-323-8479', 3: '744-521-9874'}}, 
 {'Address': {1: '12334 Hamilton Way', 2: '1234 James Rd', 3: '567 Travis St'}},
 {'City': {1: 'Toronto', 2: 'New York', 3: 'Boston'}},
 {'Country': {1: 'Canada', 2: 'USA', 3: 'USA'}},
 {'Email': {1: 'bob@gmail.com', 2: 'carlton@example.com', 3: 'fw4322@yahoo.com'}}
}

Best way is to (ab)use Pandas ;-)最好的方法是(ab)使用 Pandas ;-)

import pandas as pd
d = pd.DataFrame([result]).to_dict()
print(d)

For test case result :对于测试用例result

{'1': {'Name': 'Bob Myers', 'Phone': '410-504-5887', 'Address': '12334 Hamilton Way', 'City': 'Toronto',
'Country': 'Canada', 'Email': 'bob@gmail.com'}

Output is like:输出是这样的:

{'Name': {0: 'Bob Myers'}, 'Phone': {0: '410-504-5887'}, 'Address': {0: '12334 Hamilton Way'}, 'City': {0: 'Toronto'}, 'Country': {0: 'Canada'}, 'Email': {0: 'bob@gmail.com'}} 

Since you have a csv data file, it's better to use pandas .由于您有一个 csv 数据文件,因此最好使用pandas

import pandas as pd

a = pd.read_csv(file location)

nested_dict = a.todict()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM