python - Sorting a dictionary by key and then also sorting the list of values related to each key and outputting to CSV file?
问题描述
I am trying to sort a dictionary by key as well as value to create an output CSV file, I am having trouble getting the desired output file.
I've tried sorting the keys separately and the list of values separately but when outputting to the file the pairs are messed up.
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))
If the input is {'number': {54, 1, 95, 78, 85, 87}}, 'name': {'bob', 'steve', 'alex'}, 'color': {'blue', 'yellow', 'black'}} the output should be {'color': {'black', 'blue', 'yellow'}, 'name': {'alex', 'bob', 'steve'}, 'number': {1, 54, 78, 85, 87, 94}}
Instead I get an output that looks like {'color': {'alex', 'bob', 'steve'}, 'name': {'black', 'blue', 'yellow'}, 'number': {1, 54, 78, 85, 87, 94}} where the color and name values are swapped but in the correct order.
解决方案
here you are sorting the keys and values independently, and not linking them correctly. You need to sort with the keys first and then for the corresponding values, sort the list
Here is a working solution with 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)
推荐阅读
- c++ - 如何在 C++ 中将值放入由 VirtualAlloc 分配的内存中?
- python - 出于组织目的使用仅具有静态方法的类?
- python - ImportError:没有名为 PyQt5 的模块
- php - Laravel 5.7 错误消息“ Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException No message”
- python - PyCharm SSH 解释器 - 环境:/Program Files/Python 3.5/python.exe:没有这样的文件或目录
- r - 按行名组合/匹配/合并向量
- c# - 同步使用 HttpClient 的“正确方法”是什么?
- eclipse - 是否可以在 Eclipse 中禁用捏合缩放?
- netlogo - Netlogo 编码 - IF 代码
- r - R包未来:计划()的初始化失败