gpt4 book ai didi

python - 如何将 CSV 数据存储在具有字典和列表的嵌套字典中?

转载 作者:太空宇宙 更新时间:2023-11-04 03:43:36 25 4
gpt4 key购买 nike

我有以下 CSV 数据,

Rule1,Status1,1
Rule1,Status2,1
Rule1,Status3,1
Rule1,Status4,2
Rule2,Status1,2
Rule2,Status2,1
Rule2,Status3,1
Rule2,Status4,3

我有唯一的规则(第一列)存储在一个名为 Rules 的列表中。我希望我的字典如下所示:

DictionaryFull = {
'Rule1' : {1 : [Status1, Status2, Status3], 2 : [Status4]},
'Rule2' : {1 : [Status2, Status3], 2 : [Status1], 3 : [Status4]}
}

这是我尝试过的:

openfile = ('data.csv', 'rU')
finalfile = csv.reader(openfile, delimiter=',')

FullDictionary = {}

for row in finalfile:
for j in range (0, 300): #300 number of rules
if Rules[j] not in FullDictionary:
for i in range(1, 71): #These are third column numbers 1 - 71
if i == int(row[2]) and row[0] == Rules[j]:
FullDictionary = {Rules[j] : { i : [].append[row[1]}}
print FullDictionary

但我得到以下结果:

{'Rule1': {1 : None}} and so on

我做错了什么吗?如何完成将字典与另一个字典和列表一起使用的任务。

我试过这个:

def something():
full_dictionary = {}
with open(DataFilePath) as f:
reader = csv.reader(f)
for row in reader:
rule = row[2], status = row[0], num = int(row[5])
r = full_dictionary.setdefault(rule, {})
r.setdefault(num, []).append(status)

print full_dictionary

错误:ValueError: I/O operation on closed file

最佳答案

关于使用 collection.defaultdict :

import csv
from collections import defaultdict

full_dictionary = defaultdict(lambda: defaultdict(list))
with open('data.csv') as f:
reader = csv.reader(f)
for rule, status, num in reader:
full_dictionary[rule][num].append(status)

print full_dictionary

输出:

defaultdict(<function <lambda> at 0x00000000025A6438>, {
'Rule2': defaultdict(<type 'list'>, {
'1': ['Status2', 'Status3'],
'3': ['Status4'],
'2': ['Status1']
}),
'Rule1': defaultdict(<type 'list'>, {
'1': ['Status1', 'Status2', 'Status3'],
'2': ['Status4']
})
})

如果你不想使用defaultdict,你必须关心新 key 。

例如,使用 dict.setdefault :

import csv

full_dictionary = {}
with open('data.csv') as f:
reader = csv.reader(f)
for rule, status, num in reader:
r = full_dictionary.setdefault(rule, {})
r.setdefault(num, []).append(status)

print full_dictionary

输出:

{'Rule1': {'1': ['Status1', 'Status2', 'Status3'], '2': ['Status4']},
'Rule2': {'1': ['Status2', 'Status3'], '2': ['Status1'], '3': ['Status4']}}

关于python - 如何将 CSV 数据存储在具有字典和列表的嵌套字典中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24967286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com