gpt4 book ai didi

python - 按键对字典进行排序,然后对与每个键相关的值列表进行排序并输出到 CSV 文件?

转载 作者:行者123 更新时间:2023-12-01 07:47:25 26 4
gpt4 key购买 nike

我正在尝试按键和值对字典进行排序以创建输出 CSV 文件,但在获取所需的输出文件时遇到问题。

我尝试过分别对键和值列表进行排序,但是当输出到文件时,这些对被搞乱了。

    data = {}
with open(filename, mode = 'r') as f:
reader = csv.reader(f, delimiter = ',')
for n, row in enumerate(reader):
if not n:
continue
category, value = row
if category not in data:
data[category] = set()
data[category].add((value))

columnNames = sorted(data.keys())
columnValues = []
for value in data.values():
columnValues.append(sorted(value))

print(columnValues)
with open('sorteddata.csv', 'w') as outfile:
writer = csv.writer(outfile, delimiter = ',')
writer.writerow(columnNames)
writer.writerows(zip_longest(*columnValues))

如果输入为{'number': {54, 1, 95, 78, 85, 87}},'name': {'bob', 'steve', 'alex'}, 'color': { 'blue', 'yellow', 'black'}} 输出应为 {'color': {'black', 'blue', 'yellow'}, 'name': {'alex', 'bob', '史蒂夫'},'数字':{1, 54, 78, 85, 87, 94}}

相反,我得到的输出看起来像 {'color': {'alex', 'bob', 'steve'}, 'name': {'black', 'blue', 'yellow'}, 'number ': {1, 54, 78, 85, 87, 94}},其中颜色和名称值被交换,但顺序正确。

最佳答案

在这里,您独立地对键和值进行排序,并且没有正确链接它们。您需要先使用键排序,然后使用相应的值对列表进行排序

这是一个使用 OrderDict 的工作解决方案

import collections
inp = {
'number': {54, 1, 95, 78, 85, 87},
'name': {'bob', 'steve', 'alex'},
'color': {'blue', 'yellow', 'black'}}

ans = collections.OrderedDict()
for item in sorted(inp): # sorting with the key
val = sorted(inp[item]) # fetching the value list from the input dict
print(item, val)
ans[item] = sorted(val) # saving the item and sorted values, in the new list
print(ans)

关于python - 按键对字典进行排序,然后对与每个键相关的值列表进行排序并输出到 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56404104/

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