I have a dictionary which is like a json format. Like below:-
dito1 ={'result2':[{'math':20,'science':22,'english':31},{'math':26,'science':27,'english':33},
{'math':15,'science':55,'english':44}],'pet2':0,
'result':[{'rt':66,'io':49,'op':10},{'rt':24,'io':25,'op':5}],'pet':20}
Now I want to create a new dictionary using the above values, the new dictionary has to be seen like below:-
{'type': 'etc', 'scores': [{'math': 20, 'science': 22, 'english': 31}, {'math': 26, 'science': 27, 'english': 33}, {'math': 15, 'science': 55, 'english': 44}], 'math total': 61,'scores2':[{'math': 66, 'science': 49, 'english': 10}, {'math': 24, 'science': 25, 'english': 5}],'math total':90}
In the first dictionary there are two keys result2, result that have scores information that are lists. By using this information they must be converted as above and the math total in the second dictionary is total marks of the math's in each list. I have tried to get the desired output but I am not able to divide them into two based on the keys they belong to. The code I have tried is as follows:-
dito1 ={'result2':[{'math':20,'science':22,'english':31},{'math':26,'science':27,'english':33},
{'math':15,'science':55,'english':44}],'pet2':0,
'result':[{'rt':66,'io':49,'op':10},{'rt':24,'io':25,'op':5}],'pet':20}
reslt=[]
math_total=[]
for key,value in dito1.items():
if key == 'result' or key == 'result2':
for i in value:
for k,v in i.items():
if k == 'math':
t=v
if k == 'rt':
t=v
if k == 'science':
r=v
if k == 'io':
r=v
if k=='op':
e=v
if k=='english':
e=v
rest ={'math':t,'science':r,'english':e}
math_total.append(t)
reslt.append(rest)
final_dict={'type':'etc','math total':reslt,'scores':sum(math_total)}
print(final_dict)
The output I got is:-
{'type': 'etc', 'scores': [{'math': 20, 'science': 22, 'english': 31}, {'math': 26, 'science': 27, 'english': 33}, {'math': 15, 'science': 55, 'english': 44}, {'math': 66, 'science': 49, 'english': 10}, {'math': 24, 'science': 25, 'english': 5}], 'math total': 151}
Excepted output:-
{'type': 'etc', 'scores': [{'math': 20, 'science': 22, 'english': 31}, {'math': 26, 'science': 27, 'english': 33}, {'math': 15, 'science': 55, 'english': 44}], 'math total': 61,'scores2':[{'math': 66, 'science': 49, 'english': 10}, {'math': 24, 'science': 25, 'english': 5}],'math total2':90}
As an aside, I'd suggest re-thinking the structure/naming scheme of this final_dict; using keys like 'scores' and 'scores2' indicates you may want a list structure instead of a dict structure.
dito1 = {'result2': [{'math': 20, 'science': 22, 'english': 31}, {'math': 26, 'science': 27, 'english': 33}, {'math': 15, 'science': 55, 'english': 44}], 'pet2': 0, 'result': [{'rt': 66, 'io': 49, 'op': 10}, {'rt': 24, 'io': 25, 'op': 5}], 'pet': 20}
translate = {'rt':'math','io':'science','op':'english'}
final_dict = {'type':'etc'}
for key,list_of_dict in dito1.items():
if key in ['result', 'result2']:
score_key = key.replace('result','scores')
final_dict[score_key] = []
math_total_key = key.replace('result','math_total')
final_dict[math_total_key] = 0
for d in list_of_dict:
# translate to the intended score names as needed
for k in ['rt','io','op']:
if k in d:
d[translate[k]] = d.pop(k)
# append the scores to the appropriate nested dict
final_dict[score_key].append(dict(d))
# and increment the math_total for that set of scores
final_dict[math_total_key] += d['math']
print(final_dict)
results in
for key,value in final_dict.items():
print(f'{key}: {value}')
# Output:
type: etc
scores2: [{'math': 20, 'science': 22, 'english': 31}, {'math': 26, 'science': 27, 'english': 33}, {'math': 15, 'science': 55, 'english': 44}]
math_total2: 61
scores: [{'math': 66, 'science': 49, 'english': 10}, {'math': 24, 'science': 25, 'english': 5}]
math_total: 90
Related
marksList = [['name', ['Anand', 'Bhanu', 'Chetna', 'Durga', 'Eshwar']],
['english', [65,83,47,57,78]],
['hindi', [78,64,84,59,65]],
['maths', [85,74,74,95,84]],
['science', [58,94,59,78,68]],
['social', [72,65,82,49,65]]]
marksDict = dict(marksList)
marksDict['maths'][0]
How Can I access Anand's marks in Mathematics? Can I use the above code or is there any other way using for loop?
I would convert the list to a nicer format:
marksDict = {}
for i,name in enumerate(marksList[0][1]):
marksDict[name] = {}
for subject in marksList[1:]:
marksDict[name][subject[0]] = subject[1][i]
Output:
{
'Anand': {'english': 65, 'hindi': 78, 'maths': 85, 'science': 58, 'social': 72},
'Bhanu': {'english': 83, 'hindi': 64, 'maths': 74, 'science': 94, 'social': 65},
'Chetna': {'english': 47, 'hindi': 84, 'maths': 74, 'science': 59, 'social': 82},
'Durga': {'english': 57, 'hindi': 59, 'maths': 95, 'science': 78, 'social': 49},
'Eshwar': {'english': 78, 'hindi': 65, 'maths': 84, 'science': 68, 'social': 65}
}
Then you can access with:
marksDict['Anand']['maths']
a = {
1: {'abc': 50, 'def': 33, 'xyz': 40},
2: {'abc': 30, 'def': 22, 'xyz': 45},
3: {'abc': 15, 'def': 11, 'xyz': 50}
}
I would like to iterate through this nested dictionary, remove the sub keys (or extract the subkey values), but keep the main keys. the second step would be to turn the dictionary into a list of lists:
b = [
[1, 50, 33, 40],
[2, 30, 22, 45],
[3, 15, 11, 50]
]
I looked through the myriad of posts here talking about extracting keys and values but cannot find a close enough example to fit to what I need (still new at this): So far, I have this:
for key in a.keys():
if type(a[key]) == dict:
a[key] = a[key].popitem()[1]
which gives this - the value of the third sub key in each key: It's a start, but not complete or what I want
{1: 40, 2: 45, 3: 50}
Use a list comprehension over a.items(), use dict.values() to get the values, and then you can use unpacking (*) to get the desired lists.
>>> [[k, *v.values()] for k,v in a.items()]
[[1, 50, 33, 40], [2, 30, 22, 45], [3, 15, 11, 50]]
This solution may be not the most elegant solution, but it does what you exactly want:
a = {
1: {'abc': 50, 'def': 33, 'xyz': 40},
2: {'abc': 30, 'def': 22, 'xyz': 45},
3: {'abc': 15, 'def': 11, 'xyz': 50}
}
b = []
for key1, dict2 in a.items():
c = [key1]
c.extend(dict2.values())
b.append(c)
print(b)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
{'1': 30, '2': 15, '4': 29, '11': 22, '12': 41, '14': 26}
in this dict, how can i pair lowest key and lowest value together(it should be rising by order small to big)?
Comment ur answer.
You can use builtin function min.
(You don't need to sort).
dic = {'1': 30, '2': 15, '4': 29, '11': 22, '12': 41, '14': 26}
result = {min(dic): min(dic.values())}
print(result)
output:
{'1': 15}
here is a more compact way:
d = {'1': 30, '2': 15, '4': 29, '11': 22, '12': 41, '14': 26}
dict(zip(*map(sorted, (d, d.values()))))
output:
{'1': 15, '11': 22, '12': 26, '14': 29, '2': 30, '4': 41}
you can do in this way:
Take out the keys and values
keys=[k for k in d.keys()]
values = [v for v in d.values()]
create new dict
values.sort()
keys.sort()
new_dict= dict(zip(keys,values))
Output:
{'1': 15, '11': 22, '12': 26, '14': 29, '2': 30, '4': 41}
a = {'1': 30, '2': 15, '4': 29, '11': 22, '12': 41, '14': 26}
print(dict(zip(sorted(a.keys(), key=lambda x:int(x)), sorted(a.values()))))
# {'1': 15, '2': 22, '4': 26, '11': 29, '12': 30, '14': 41}
I have the following nested dictionary and need to figure out how to sum all 'qty'.
data1 = {
'Batch1': {
'Pink': {'qty': 25, 'ordered': 15},
'Blue': {'qty': 18, 'ordered': 20}
},
'Batch2': {
'Coke': {'qty': 50, 'ordered': 100},
'Sprite': {'qty': 30, 'ordered': 25}
}
}
So the outcomes would be 123.
You can use sum:
data1 = {'Batch1': {'Pink': {'qty': 25, 'ordered':15}, 'Blue': {'qty':18, 'ordered':20}}, 'Batch2': {'Coke': {'qty': 50, 'ordered': 100},'Sprite': {'qty':30, 'ordered':25}}}
result = sum(b['qty'] for c in data1.values() for b in c.values())
Output:
123
Your data1 was formatted funny, so here's what I used:
{'Batch1': {'Blue': {'ordered': 20, 'qty': 18},
'Pink': {'ordered': 15, 'qty': 25}},
'Batch2': {'Coke': {'ordered': 100, 'qty': 50},
'Sprite': {'ordered': 25, 'qty': 30}}}
If you're not sure how deeply nested your dict will be, you can write a function to recursively traverse the nested dict looking for the qty key and sum the values:
def find_key_vals(query_key, base_dict):
values = []
for k, v in base_dict.items():
if k == query_key:
values.append(v)
elif isinstance(v, dict):
values += find_key_vals(query_key, v)
return values
find_key_vals('qty', data1)
# => [50, 30, 25, 18]
sum(find_key_vals('qty', data1))
# => 123
I have below list of dictionaries
input=[{'pid': 66, 'ids': [{'stid': 20, 'st': 20}, {'stid': 21, 'st': 60}, {'stid': 22, 'st': 20}, {'stid': 23, 'st': 60}, {'stid': 24, 'st': 20}], 'count': 5}, {'pid': 27, 'ids': [{'stid': 20, 'st': 20}, {'stid': 22, 'st': 20}, {'stid': 23, 'st': 60}, {'stid': 24, 'st': 20}], 'count': 4}, {'pid': 29, 'ids': [{'stid': 20, 'st': 20}, {'stid': 24, 'st': 20}], 'count': 2}]
Am trying to get the output as below -
res = [66,27,29]
res contain the pid values in array.
For this, I tried below code to get only the 'pid' item from input
fs_loc = []
for g, items in itertools.groupby(input, lambda x: (x['pid'])):
fs_loc.append({ 'pid': g[0] })
print(fs_loc)
This throws an error int is not subscriptable.
The same code works fine if I wanted to retain pid,count - for this below works -
fs_loc = []
for g, items in itertools.groupby(input, lambda x: (x['pid'],x['count'])):
fs_loc.append({ 'pid': g[0], 'count': g[1] })
print(fs_loc)
How can I get the array list of pid values ?
res = [66,27,29]
Simple, just iterate over the list items and get the value of key pid from dict through dict.get() method.
>>> input_ =[{'pid': 66, 'ids': [{'stid': 20, 'st': 20}, {'stid': 21, 'st': 60}, {'stid': 22, 'st': 20}, {'stid': 23, 'st': 60}, {'stid': 24, 'st': 20}], 'count': 5}, {'pid': 27, 'ids': [{'stid': 20, 'st': 20}, {'stid': 22, 'st': 20}, {'stid': 23, 'st': 60}, {'stid': 24, 'st': 20}], 'count': 4}, {'pid': 29, 'ids': [{'stid': 20, 'st': 20}, {'stid': 24, 'st': 20}], 'count': 2}]
>>> [i['pid'] for i in input_]
[66, 27, 29]
or
[i.get('pid') for i in input_]
You can use setdefault. Please note that I changed the variable name of your original list to input_data. It's not a good idea to use input for a variable name.
d = {}
for e in input_data:
for i,j in e.items():
d.setdefault(i, []).append(j)
res = d['pid']
print (res)
Output:
[66, 27, 29]
Easy way,
>>> data = [{'count': 5, 'pid': 66, 'ids': [{'stid': 20, 'st': 20}, {'stid': 21, 'st': 60}, {'stid': 22, 'st': 20}, {'stid': 23, 'st': 60}, {'stid': 24, 'st': 20}]}, {'count': 4, 'pid': 27, 'ids': [{'stid': 20, 'st': 20}, {'stid': 22, 'st': 20}, {'stid': 23, 'st': 60}, {'stid': 24, 'st': 20}]}, {'count': 2, 'pid': 29, 'ids': [{'stid': 20, 'st': 20}, {'stid': 24, 'st': 20}]}]
>>> map(lambda x: x['pid'], data)
[66, 27, 29]