Home > front end >  Python return a dictionary that groups value by same key
Python return a dictionary that groups value by same key

Time:10-21

I have a file with this format:

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

and is trying to create a dictionary with clas as keys and groups name based on it:

#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)

The function is expected to output a dictionary with "clas" as keys with corresponding "name" values.

However currently the output is {'a': ['x1'], 'b': ['x3'], 'c': ['x4'], 'd': ['x5']} which does include "name" values with the same key.

Not sure what conditions to write to make dictionary output correctly,so are there ways to make the output to be {'a': ['x1'], 'b': ['x2','x3'], 'c': ['x4'], 'd': ['x5']}with only default python functions?...

CodePudding user response:

Use a defaultdict with list values & append to it instead of overwriting.

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)

CodePudding user response:

Umm I managed to get the expected result with this:

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