Home > Back-end >  Fetching the common keys with values using python dictionary comprehension
Fetching the common keys with values using python dictionary comprehension

Time:08-26

I am new to python and currently trying my way out on python dictionary comprehension. I am currently trying to fetch common keys and their values from a python dictionary using dictionary comprehension. I have tried few options but it doesn't seem to fetch the desired output. Could someone kindly point me to the right direction please.

input = [
    {'name': 'xxx','class':'1','grade':'A '},
    {'name': 'yyy','class':'1','grade':'A-'},
    {'name': 'zzz','class':'2','grade':'B '},
    {'name': 'ooo','class':'1','grade':'C '},
    {'name': 'ppp','class':'2','grade':'C '},
    {'name': 'sss','class':'3','grade':'A '}
   ]

Expected output:

output = [
 {'class':'1','grade':['A ','A-','C '],'name':['xxx','yyy','ooo']},
 {'class':'2','grade':['B ','C '],'name':['zzz','ppp']},
 {'class':'3','grade':['A '],'name':['sss']}
 ]

CodePudding user response:

This should get the job done:

input = [
{'name': 'xxx','class':'1','grade':'A '},
{'name': 'yyy','class':'1','grade':'A-'},
{'name': 'zzz','class':'2','grade':'B '},
{'name': 'ooo','class':'1','grade':'C '},
{'name': 'ppp','class':'2','grade':'C '},
{'name': 'sss','class':'3','grade':'A '}
]

output = []

#This will make a new list of dictionaries 
#without the duplicate 'class' keys 
for list_item in input:
    if {'class': list_item['class']} not in output:
        output.append({"class": list_item['class']})

#This will create new keys named 'grade' and 'name'
#for every item in the new list of dictionaries
for dict_ in output:
    dict_.update({'grade': []})
    dict_.update({'name': []})
    for list_item in input:
        #This will populate the lists inside the new keys 
        #with the correct values     
        if list_item['class'] == dict_['class']:
            dict_['grade'].append(list_item['grade'])
            dict_['name'].append(list_item['name'])

print(output)

CodePudding user response:

Not sure if this is possible with a dictionary comprehension but you can do it with a basic loop iterating over the input list...

input_ = [
    {'name': 'xxx', 'class': '1', 'grade': 'A '},
    {'name': 'yyy', 'class': '1', 'grade': 'A-'},
    {'name': 'zzz', 'class': '2', 'grade': 'B '},
    {'name': 'ooo', 'class': '1', 'grade': 'C '},
    {'name': 'ppp', 'class': '2', 'grade': 'C '},
    {'name': 'sss', 'class': '3', 'grade': 'A '}]

output_ = {}

for d in input_:
    d_ = output_.setdefault(d['class'], {'class': d['class']})
    d_.setdefault('grade', []).append(d['grade'])
    d_.setdefault('name', []).append(d['name'])

print(list(output_.values()))

Output:

[{'class': '1', 'grade': ['A ', 'A-', 'C '], 'name': ['xxx', 'yyy', 'ooo']}, {'class': '2', 'grade': ['B ', 'C '], 'name': ['zzz', 'ppp']}, {'class': '3', 'grade': ['A '], 'name': ['sss']}]

CodePudding user response:

try this code for solving your problem which makes use of mainly list comprehensions:

input = [
    {'name': 'xxx','class':'1','grade':'A '},
    {'name': 'yyy','class':'1','grade':'A-'},
    {'name': 'zzz','class':'2','grade':'B '},
    {'name': 'ooo','class':'1','grade':'C '},
    {'name': 'ppp','class':'2','grade':'C '},
    {'name': 'sss','class':'3','grade':'A '}
   ]

all_classes = list(set([int(i['class']) for i in input]))
all_classes  = [str(i) for i in all_classes]
print('all classes: ',all_classes)
    
result = []
for i in all_classes:
    class_dict = {'class':i,
            'grade': [j['grade'] for j in input if j['class'] == i],
            'name':  [j['name'] for j in input if j['class'] == i]
        }
    result.append(class_dict)
    
print(result)

Output

all classes:  ['1', '2', '3']
[
{'class': '1', 'grade': ['A ', 'A-', 'C '], 'name': ['xxx', 'yyy', 'ooo']},
{'class': '2', 'grade': ['B ', 'C '], 'name': ['zzz', 'ppp']},
{'class': '3', 'grade': ['A '], 'name': ['sss']}]
  • Related