【问题标题】:Python return a dictionary that groups value by same keyPython返回一个按相同键对值进行分组的字典
【发布时间】:2021-10-20 15:21:10
【问题描述】:

我有一个格式如下的文件:

name  x   y  clas  
x1    1   1   A
x2    2   2   B
x3    3   3   B
x4    4   4   C
x5    5   5   D

并且正在尝试创建一个以clas 作为键的字典,并基于它创建name 组:

#Just reading reading the file in
data = {}
with open('sample.csv') as file:        
    next(file) 
    reads = file.readlines()
    for lines in reads:
        line = lines.strip('\n').lower()
        (name, x, y, clas) = line.split(",")
        data[name] = x,y,clas

#How to assign "array" values based on their "clas"
dictionary = {}
array = ['x1', 'x2', 'x3', 'x4', 'x5']
for i in range(len(array)):
   classs = data.get(array[i])[2]
   dictionary[classs] = [array[i]]
print(dictionary)

该函数应该输出一个字典,其中“clas”作为键,对应的“name”值。

但目前的输出是{'a': ['x1'], 'b': ['x3'], 'c': ['x4'], 'd': ['x5']},其中包含具有相同键的“名称”值。

不知道要写什么条件才能正确输出字典,那么有没有办法让输出成为{'a': ['x1'], 'b': ['x2','x3'], 'c': ['x4'], 'd': ['x5']}只有默认的python函数?...

【问题讨论】:

  • 您只是每次都覆盖上一个密钥:dictionary[classs] = [array[i]]...想想您将如何处理这个...检查密钥是否已经存在,如果不存在,请使用与上面相同的分配,如果是,追加到已经存在的列表
  • 顺便说一句,停止迭代range(len(array)),直接迭代array

标签: python python-3.x dictionary


【解决方案1】:

使用带有list 值的defaultdict 并附加到它而不是覆盖。

dictionary = defaultdict(list)
array = ['x1', 'x2', 'x3', 'x4', 'x5']
for i in range(len(array)):
   classs = data.get(array[i])[2]
   dictionary[classs].append(array[i])
print(dictionary)

【讨论】:

    【解决方案2】:

    嗯,我设法得到了预期的结果:

    dictionary = {}
    for key, value in sorted(data.items()):
        dictionary.setdefault(value[2], []).append(key)
    print(dictionary)
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2013-08-13
    • 2023-01-22
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多