如果键是列表中的键,如何在词典的csv文件中存储键?

2024-06-02 13:23:51 发布

您现在位置:Python中文网/ 问答频道 /正文

这些输出存储在csv文件中:

go:[u'forward', u'always', u'somewhere', u'very', u'now', u'somewhere', u'up']
incorrect:[u'little']
hide:[u'somewhere']
had:[u'little']
jiggle: [u'forward', u'little', u'little']

这是一个程序的输出。我是从:

for a in consolidated:
    print a, consolidated[a]
    writer2.writerow([a, consolidated[a]])

现在,当我要检索值时,它会产生问题。 例如

for i in consolidated[a]:
     print i

它没有给出键的值。如何检索键的每个值?你知道吗

或者我怎样才能像这样存储它:

(go,u'forward', u'always', u'somewhere', u'very', u'now', u'somewhere', u'up')

Tags: 文件csvingoforalwaysnowvery
2条回答

好的,假设您有一个包含数组值的字典,并且希望将它们存储为csv格式:"key", "val1,val2,val3",其中"是csv引用字符,,是delimeter。你知道吗

这就是你存储和阅读的方式。你知道吗

import csv

options = {
    "delimiter" : ",",
    "quotechar" : "\"",
    "quoting"   : csv.QUOTE_MINIMAL
}

def create(dic, filename):
    data = []
    for key, values in dic.items():
        data.append([key, options['delimiter'].join(values)])

    with open(filename, 'wb') as csvfile:
        spamwriter = csv.writer(csvfile, **options)
        for line in data:
            spamwriter.writerow(line)

def readFile(filename, _unicode=False):
    data = {}
    with open(filename, 'rb') as csvfile:
        spamreader = csv.reader(csvfile, **options)
        for row in spamreader:
            values = row[1].split(options['delimiter'])
            if _unicode:
                values = [unicode(value) for value in values]
            data[row[0]] = values
    return data


d = {
    "Hello" : ['aa','bb','cc','dd'],
    "World" : ['e','f','g','h']
}

filename = "dataFile.csv"
create(d, filename)

# print as strings
print readFile(filename)
print readFile(filename, True)

这将输出以下内容:

# string values
{
    'World': ['e', 'f', 'g', 'h'], 
    'Hello': ['aa', 'bb', 'cc', 'dd']
}
# unicode values
{
    'World': [u'e', u'f', u'g', u'h'], 
    'Hello': [u'aa', u'bb', u'cc', u'dd']
}

当你打开csv文件时,它看起来是这样的:

CSV File

假设您有一个带有键goincorrecthad等的字典d,并且它们的值是列表,则可以将其写入文件:

s='' 
for k,v in d.items():
    s += "{},{}\n".format(k,','.join(v))
with open('myfile.txt','w') as f:
    f.write(s)

请注意,该键将对应于每行的第一个字符串,例如go,forward,always,...\nincorrect,little

csv应该在每一行上有相同数量的值/逗号,因此如果您有一个可变长度的列表要保存到文件中,它可能不是您想要的。 要检索数据,可以执行以下操作:

d={}
with open('myfile.txt','r') as f:
    for line in f:
        words=line.split(',')
        d[words[0]] = words[1:]

如果需要格式化为unicode,可以使用codecs.open(file,'w','utf-8')之类的格式。你知道吗

相关问题 更多 >