我有一个字典,用于存储每个键的项目列表,如下所示:
name_dict = {'MiddleName': ['H.', 'T.'], 'LastName': ['Perkins', 'Joseph'], 'FirstName': ['Elizabeth ', 'Scott ']}
我想以字典格式打印字典中的数据:
FirstName,MiddleName,LastName # the keys of the dictionary
Elizabeth,H.,Perkins #the values of the keys in one line (the first item in the list)
Scott,T.,Joseph #the values of the keys in new line (the following item in the list)
如何解决这个问题?
我已尝试通过Gareth Latty执行建议的解决方案,但这不起作用。
with open('C:/Output.csv',"w+") as file:
w = csv.DictWriter(file,name_dict.keys())
w.writeheader()
w.writerow(name_dict)
输出以下内容:
MiddleName,LastName,FirstName
"['H.', 'T.']","['Perkins', 'Joseph']","['Perkins', 'Joseph']"
知道如何输出新行中每个键的值(列表中的项目)吗?
答案 0 :(得分:1)
我认为你滥用dict
。如果您有多个值,则应使用list
dicts
而不是dict
,其值为lists
。而不是
Dict = {'MiddleName': ['H.', 'T.'], 'LastName': ['Perkins', 'Joseph'], 'FirstName': ['Elizabeth ', 'Scott ']}
你应该这样做:
Dict = [{'FirstName': 'Elizabeth', 'MiddleName': 'H.', 'LastName': 'Perkins'}, {'FirstName': 'Joseph', 'MiddleName': 'T. ', 'LastName': 'Scott'}]
或更易阅读的版本:
Dict = [
{'FirstName': 'Elizabeth', 'MiddleName': 'H.', 'LastName': 'Perkins'},
{'FirstName': 'Joseph', 'MiddleName': 'T. ', 'LastName': 'Scott' }
]
如果你想打印一行(列表中的一个字典),你可以这样做:
def printDict(d):
print d["FirstName"] + "," + d["MiddleName"] + "," + d["LastName"]
如果您想打印列表中的每个元素:
def printList(l):
for i in l:
printDict(i)
就这样使用它:
printList(Dict)
使用您的第一个(原始)Dict
,访问Dict["FirstName"]
将返回list
,并且在打印时将打印为:
[" Elizabeth"," Joesph"]
但是使用第二种(我建议的新方式)Dict
,访问Dict[0]["FirstName"]
会返回string
,并打印如下:
伊丽莎白
答案 1 :(得分:1)
csv.DictWriter
期望每行有field:single_line
对的字典,遗憾的是不是你拥有的字典,你基本上需要将你的数据结构转换为单行的dicts列表: / p>
[{'MiddleName': 'H.', 'FirstName': 'Elizabeth ', 'LastName': 'Perkins'}, {'MiddleName': 'T.', 'FirstName': 'Scott ', 'LastName': 'Joseph'}]
您可以使用以下内容进行转换:
import csv
def seperate_entries(dict_of_lists):
iters = [(k,iter(v)) for k,v in dict_of_lists.items()]
try:
while True:
yield {k:next(v) for k,v in iters}
except StopIteration:
return
name_dict = {'MiddleName': ['H.', 'T.'], 'LastName': ['Perkins', 'Joseph'], 'FirstName': ['Elizabeth ', 'Scott ']}
with open('sample.csv',"w+") as file:
w = csv.DictWriter(file,name_dict.keys())
w.writeheader()
w.writerows(seperate_entries(name_dict))
答案 2 :(得分:0)
要访问词典中的键,您只需执行以下操作:
middleNames=Dict['Middlename']
firstNames=Dict['FirstName']
lastNames=Dict['LastName']
您现在可以访问存储在内部列表信息中的值,这可以通过以下方式访问:
# Find how many items read (optional)
len(middleNames)
# Then iterate through the items
for mName in middleName:
print mName # this will print each list item e.g.
小时。
吨。
# for brevity, this is the same as doing this...
middleName[0] etc
希望这有帮助。
答案 3 :(得分:0)
我确信有更有效的方法可以达到你想要的效果,但这可以简单概述你想要的东西,并展示你如何实现它。
names = {'MiddleName': ['H.', 'T.'], 'LastName': ['Perkins', 'Joseph'], 'FirstName': ['Elizabeth ', 'Scott ']}
output = open('output.txt','w')
#NOTE: this will write headers in alphabetical format. You will need to change that so it follows the FirstName, MiddleName, LastName pattern
for key in sorted(names.keys()):
output.write(key + ',')
output.write('\n')
#assuming we always have same amount of middle, first, and last names
for i in range(len(names['FirstName'])):
personFname = ''
personLname = ''
personMname = ''
for key in names.keys():
if key == 'MiddleName':
personMname = names[key][i]
elif key == 'FirstName':
personFname = names[key][i]
elif key == 'LastName':
personLname = names[key][i]
output.write(personFname + ',' + personMname + ',' + personLname)
output.write('\n')
output.close()
答案 4 :(得分:0)
您需要定义您拥有的行数。 只需在Dict中将所有键平放到行中即可。
import csv
Dict = {'MiddleName': ['H.', 'T.'], 'LastName': ['Perkins', 'Joseph'], 'FirstName': ['Elizabeth ', 'Scott ']}
len_row = 2
with open('Output.csv', "w+") as file:
w = csv.DictWriter(file, Dict.keys())
w.writeheader()
for i in range(len_row):
row = {}
for k in Dict.keys():
for v in Dict.values():
row[k] = Dict[k][i]
w.writerow(row)