I am trying to sort a dictionary within a dictionary. My goal is to sort the 'sub' dictionary ['extra'] based on it's values, from high to low.The problem I'm having is that my 'sub' dictionary is nested deep within the main dictionary. Using other examples, I can do this for one level higher, see my code below. So instead of sorting 'marks', I would like to sort the items 1,2 & 3 based on their values. Code:
# initializing dictionary
test_dict = {'Nikhil' : { 'roll' : 24, 'marks' : 17, 'extra' : {'item1': 2, 'item2': 3, 'item3': 5}},
'Akshat' : {'roll' : 54, 'marks' : 12, 'extra' : {'item1': 8, 'item2': 3, 'item3': 4}},
'Akash' : { 'roll' : 12, 'marks' : 15, 'extra' : {'item1': 9, 'item2': 3, 'item3': 1}}}
# printing original dict
print("The original dictionary : " + str(test_dict))
# using sorted()
# Sort nested dictionary by key
res = sorted(test_dict.items(), key = lambda x: x[1]['marks'])
# print result
print("The sorted dictionary by marks is : " + str(res))
# How to sort on 'extra'?
So this is what I want it to look like:
sorted_dict = {'Nikhil' : { 'roll' : 24, 'marks' : 17, 'extra' : {'item3': 5, 'item2': 3, 'item1': 2}},
'Akshat' : {'roll' : 54, 'marks' : 12, 'extra' : {'item1': 8, 'item3': 4, 'item2': 3}},
'Akash' : { 'roll' : 12, 'marks' : 15, 'extra' : {'item1': 9, 'item2': 3, 'item3': 1}}}
Well this seems to do it:
test_dict = {
'Nikhil': {'roll': 24, 'marks': 17, 'extra': {'item1': 2, 'item2': 3, 'item3': 5}},
'Akshat': {'roll': 54, 'marks': 12, 'extra': {'item1': 8, 'item2': 3, 'item3': 4}},
'Akash': {'roll': 12, 'marks': 15, 'extra': {'item1': 9, 'item2': 3, 'item3': 1}}
}
sorted_dict = test_dict.copy()
for name in test_dict:
extra = test_dict[name]['extra']
sorted_extra = dict(reversed(sorted(extra.items(), key=lambda item: item[1])))
sorted_dict[name]['extra'] = sorted_extra
this sorts the values but not the keys of the 'extra' dict for all dicts in the big dictionary:
test_dict = {
'Nikhil': {'roll': 24, 'marks': 17, 'extra': {'item1': 2, 'item2': 3, 'item3': 5}},
'Akshat': {'roll': 54, 'marks': 12, 'extra': {'item1': 8, 'item2': 3, 'item3': 4}},
'Akash': {'roll': 12, 'marks': 15, 'extra': {'item1': 9, 'item2': 3, 'item3': 1}}
}
for dct in test_dict.values():
extra_keys, extra_values = dct['extra'].keys(), dct['extra'].values()
dct['extra'] = dict(zip(extra_keys, sorted(extra_values, reverse=True)))
print(test_dict)
output:
{'Nikhil': {'roll': 24, 'marks': 17, 'extra': {'item1': 5, 'item2': 3, 'item3': 2}},
'Akshat': {'roll': 54, 'marks': 12, 'extra': {'item1': 8, 'item2': 4, 'item3': 3}},
'Akash': {'roll': 12, 'marks': 15, 'extra': {'item1': 9, 'item2': 3, 'item3': 1}}}
Same thing can also be achived by List Comprehension
test_dict = {
'Nikhil': {'roll': 24, 'marks': 17, 'extra': {'item1': 2, 'item2': 3, 'item3': 5}},
'Akshat': {'roll': 54, 'marks': 12, 'extra': {'item1': 8, 'item2': 3, 'item3': 4}},
'Akash': {'roll': 12, 'marks': 15, 'extra': {'item1': 9, 'item2': 3, 'item3': 1}}
}
result = {
k: {
m: dict(sorted(n.items(), reverse=True, key=lambda x: x[1]))
if m == 'extra' else n
for (m, n) in v.items()
} for (k, v) in test_dict.items()
}
print(result)
sort the inner dict and assign it to test_dict[key]['extra'].. just with a loop
for key in test_dict.keys():
test_dict[key]["extra"] = dict(sorted(test_dict[key]["extra"].items(), key=itemgetter(1), reverse=True))
than the test_dict output would be as
{
'Nikhil': {'roll': 24, 'marks': 17, 'extra': {'item3': 5, 'item2': 3, 'item1': 2}},
'Akshat': {'roll': 54, 'marks': 12, 'extra': {'item1': 8, 'item3': 4, 'item2': 3}},
'Akash': {'roll': 12, 'marks': 15, 'extra': {'item1': 9, 'item2': 3, 'item3': 1}}
}
Related
I have a list of items (dicts) that I have in a variable which was dumped from a MySQL select. Each dict in this list is a row from the MySQL Table. There is an id for each dict and there is also a specific id which can be duplicated in this list, and not always in order. I am trying to loop through this list and get all the data from the rows with similar specific IDs. I will then do something with that data like find price averages, max/min, etc. This table in MySQL is also a temp table, where I'm pulling this info, doing these calculations, then dumping it to a new MySQL table.
An example of the data in the list would be:
{'id': 1, 'item_id': 27, 'item_price': 1.5, 'item_length': 23, 'item_width': 12, 'item_depth': 16}
{'id': 2, 'item_id': 28, 'item_price': 1.5, 'item_length': 23, 'item_width': 12, 'item_depth': 16}
{'id': 3, 'item_id': 27, 'item_price': 1.5, 'item_length': 23, 'item_width': 12, 'item_depth': 16}
{'id': 4, 'item_id': 29, 'item_price': 1.5, 'item_length': 23, 'item_width': 12, 'item_depth': 16}
{'id': 5, 'item_id': 28, 'item_price': 1.5, 'item_length': 23, 'item_width': 12, 'item_depth': 16}
{'id': 6, 'item_id': 27, 'item_price': 1.5, 'item_length': 23, 'item_width': 12, 'item_depth': 16}
{'id': 7, 'item_id': 29, 'item_price': 1.5, 'item_length': 23, 'item_width': 12, 'item_depth': 16}
I want to go through each one, get all of the lines that have item_id of 27, do something with that data, then get all of the lines with item_id of 28, do something with that data, and so on.
I did try a temp_id value setting, but this would be set each time that item_id would change.
tempID = 0
for item in itemList:
if item["item_id"] != tempID:
tempID = item["item_id"]
<gather data>
I think I'm on the right track with setting tempIDs, but not sure how to set them where it goes through the entire list until that same id it first saw is completed and there are no more lines left.
One way to achieve this by organising your data based on "item_id", which will help you in fetching records cleanly. Here I am grouping your data by creating a dictionary with "item_id" as key. Here's a "one-liner" using dictionary comprehension along with the usage of sorted(), collections.groupby() and operator.itemgetter() to create the dictionary as:
my_list = [
{'id': 1, 'item_id': 27, 'item_price': 1.5, 'item_length': 23, 'item_width': 12, 'item_depth': 16},
{'id': 2, 'item_id': 28, 'item_price': 1.5, 'item_length': 23, 'item_width': 12, 'item_depth': 16},
{'id': 3, 'item_id': 27, 'item_price': 1.5, 'item_length': 23, 'item_width': 12, 'item_depth': 16},
{'id': 4, 'item_id': 29, 'item_price': 1.5, 'item_length': 23, 'item_width': 12, 'item_depth': 16},
{'id': 5, 'item_id': 28, 'item_price': 1.5, 'item_length': 23, 'item_width': 12, 'item_depth': 16},
{'id': 6, 'item_id': 27, 'item_price': 1.5, 'item_length': 23, 'item_width': 12, 'item_depth': 16},
{'id': 7, 'item_id': 29, 'item_price': 1.5, 'item_length': 23, 'item_width': 12, 'item_depth': 16}
]
from itertools import groupby
from operator import itemgetter
my_dict = {x: list(l) for x, l in groupby(sorted(my_list, key=itemgetter('item_id')), key=itemgetter('item_id'))}
which will return my_dict as:
{
27: [
{'item_price': 1.5, 'id': 1, 'item_id': 27, 'item_depth': 16, 'item_width': 12, 'item_length': 23},
{'item_price': 1.5, 'id': 3, 'item_id': 27, 'item_depth': 16, 'item_width': 12, 'item_length': 23},
{'item_price': 1.5, 'id': 6, 'item_id': 27, 'item_depth': 16, 'item_width': 12, 'item_length': 23}
],
28: [
{'item_price': 1.5, 'id': 2, 'item_id': 28, 'item_depth': 16, 'item_width': 12, 'item_length': 23},
{'item_price': 1.5, 'id': 5, 'item_id': 28, 'item_depth': 16, 'item_width': 12, 'item_length': 23}
],
29: [
{'item_price': 1.5, 'id': 4, 'item_id': 29, 'item_depth': 16, 'item_width': 12, 'item_length': 23},
{'item_price': 1.5, 'id': 7, 'item_id': 29, 'item_depth': 16, 'item_width': 12, 'item_length': 23}
]
}
Now you can iterate this dict and utilize your data as you need like:
for k, v in my_dict.items():
# Do whatever you want with the data
print("Key: {} - data: {}".format(k, str(v)))
# Prints:
# Key: 27 - data: [{'item_price': 1.5, 'id': 1, 'item_id': 27, 'item_depth': 16, 'item_width': 12, 'item_length': 23}, {'item_price': 1.5, 'id': 3, 'item_id': 27, 'item_depth': 16, 'item_width': 12, 'item_length': 23}, {'item_price': 1.5, 'id': 6, 'item_id': 27, 'item_depth': 16, 'item_width': 12, 'item_length': 23}]
# Key: 28 - data: [{'item_price': 1.5, 'id': 2, 'item_id': 28, 'item_depth': 16, 'item_width': 12, 'item_length': 23}, {'item_price': 1.5, 'id': 5, 'item_id': 28, 'item_depth': 16, 'item_width': 12, 'item_length': 23}]
# Key: 29 - data: [{'item_price': 1.5, 'id': 4, 'item_id': 29, 'item_depth': 16, 'item_width': 12, 'item_length': 23}, {'item_price': 1.5, 'id': 7, 'item_id': 29, 'item_depth': 16, 'item_width': 12, 'item_length': 23}]
If you can/want to use pandas, the pd.DataFrame.from_records can be helpful.
Just use it as item_df = pd.DataFrame.from_records(itemList) and use pandas groupby to compute the statistics
I have several dictionaries in a list with this structure:
[{'store': 'walmart',
'store_id': 0,
'store_info': {'grapes': {'availability': {'No': 1, 'Yes': 1}},
'tomatoes': {'availability': {'No': 5, 'Yes': 6}},
'oranges': {'availability': {'No': 2, 'Yes': 2}},
'bottled water': {'availability': {'No': 10, 'Yes': 5}},
"india's mangos": {'availability': {'No': 3, 'Yes': 5}},
'water melon': {'availability': {'No': 2, 'Yes': 2}},
'lemons': {'availability': {'No': 2, 'Yes': 3}},
'kiwifruit': {'availability': {'No': 4, 'Yes': 2}},
'pineapple': {'availability': {'No': 5, 'Yes': 20}},
'total_yes': 23,
'total_no': 23,
'total': 46,
'id': [3, 4, 6, 2, 1, 6, 1, 4, 2]}},
{'store': 'Costco',
'store_id': 24,
'store_info': {'papaya': {'availability': {'No': 1, 'Yes': 1}},
'lychee': {'availability': {'No': 5, 'Yes': 1}},
'fig': {'availability': {'No': 2, 'Yes': 2}},
'blackberry': {'availability': {'No': 2, 'Yes': 5}},
"india's mangos": {'availability': {'No': 3, 'Yes': 5}},
'plum': {'availability': {'No': 1, 'Yes': 2}},
'total_yes': 43,
'total_no': 3,
'total': 46,
'id': [3, 4, 36, 2, 1, 1, 2, 4, 2]}}
]
How can I filter all the Yes and No values which are greater or equal to 5 at the same time? For example, given the above dict. The expected output should look like this if the dictionary fullfil the condition:
[
{'store': 'walmart',
'store_id': 0,
'store_info': {
'tomatoes': {'availability': {'No': 5, 'Yes': 6}},
'bottled water': {'availability': {'No': 10, 'Yes': 5}},
'pineapple': {'availability': {'No': 5, 'Yes': 20}},
'total_yes': 23,
'total_no': 23,
'total': 46,
'id': [3, 4, 6, 2, 1, 6, 1, 4, 2]}
}
]
In the above example, 'india's mangos': {'availability': {'No': 3, 'Yes': 5}} should be filtered or removed. Because, although the 5 fullfil Yes treshold, the key No, doesnt fulfill the treshold at the same time. Alternatively, 'pineapple': {'availability': {'No': 5, 'Yes': 20}}, should remain in the dict, because Yes key has as values 20, which is greater than the 5 threshold. Finally, the second dict (costco) should be removed because none of its keys are at leas 5.
So far I tried to iterate over the structure, however, I am making too many loops, is there a more compact way of getting the expected output?:
a_lis = []
for e in list_dict:
try:
l = list(e['store_info'].keys())
for i in l:
#print(e['store_info'][i]['availability'])
if e['store_info'][i]['availability']['No']>=5 and e['availability'][i]['availability']['Yes']>= 5:
a_lis.append(e['store_info'][i]['availability'])
print(a_lis)
else:
pass
except TypeError:
pass
That's not difficult.I would recommend you create a new list.(And revise the dictionary directly.)
lst = [{'store': 'walmart',
'store_id': 0,
'store_info': {'grapes': {'availability': {'No': 1, 'Yes': 1}},
'tomatoes': {'availability': {'No': 5, 'Yes': 6}},
'oranges': {'availability': {'No': 2, 'Yes': 2}},
'bottled water': {'availability': {'No': 10, 'Yes': 5}},
'india\'s mangos': {'availability': {'No': 3, 'Yes': 5}},
'water melon': {'availability': {'No': 2, 'Yes': 2}},
'lemons': {'availability': {'No': 2, 'Yes': 3}},
'kiwifruit': {'availability': {'No': 4, 'Yes': 2}},
'pineapple': {'availability': {'No': 5, 'Yes': 20}},
'total_yes': 23,
'total_no': 23,
'total': 46,
'id': [3, 4, 6, 2, 1, 6, 1, 4, 2]}},
{'store': 'Costco',
'store_id': 24,
'store_info': {
'papaya': {'availability': {'No': 1, 'Yes': 1}},
'lychee': {'availability': {'No': 5, 'Yes': 1}},
'fig': {'availability': {'No': 2, 'Yes': 2}},
'blackberry': {'availability': {'No': 2, 'Yes': 5}},
'india\'s mangos': {'availability': {'No': 3, 'Yes': 5}},
'plum': {'availability': {'No': 1, 'Yes': 2}},
'total_yes': 43,
'total_no': 3,
'total': 46,
'id': [3, 4, 36, 2, 1, 1, 2, 4, 2]}}
]
result_list = []
for sub_dict in lst:
if sub_dict['store_info']['total_yes'] >= 5 and sub_dict['store_info']['total_no'] >= 5:
result_list.append(sub_dict)
key_need_to_be_removed = [k for k, v in sub_dict['store_info'].items() if type(v) is dict and (v['availability']['Yes'] < 5 or v['availability']['No'] < 5)]
for k in key_need_to_be_removed: # remove the dict under dictionary['store_info']
del sub_dict['store_info'][k]
print(result_list)
Result:
[{
'store': 'walmart',
'store_id': 0,
'store_info': {
'tomatoes': {
'availability': {
'No': 5,
'Yes': 6
}
},
'bottled water': {
'availability': {
'No': 10,
'Yes': 5
}
},
'pineapple': {
'availability': {
'No': 5,
'Yes': 20
}
},
'total_yes': 23,
'total_no': 23,
'total': 46,
'id': [3, 4, 6, 2, 1, 6, 1, 4, 2]
}
}]
Here is another approach:
# where data is the input
filtered = []
for store in data:
avail_dict = {}
extra_dict = {}
for item, value in store['store_info'].items():
if isinstance(value, dict):
okay = value['availability'].get('No',0) >= 5 and value['availability'].get('Yes',0) >= 5
if okay:
avail_dict[item] = value
else:
extra_dict[item] = value
if avail_dict:
avail_dict.update(extra_dict)
new_store = dict(store)
new_store['store_info'] = avail_dict
filtered.append(new_store)
Result for filtered (input data is unchanged):
[{'store': 'walmart',
'store_id': 0,
'store_info': {'tomatoes': {'availability': {'No': 5, 'Yes': 6}},
'bottled water': {'availability': {'No': 10, 'Yes': 5}},
'pineapple': {'availability': {'No': 5, 'Yes': 20}},
'total_yes': 23,
'total_no': 23,
'total': 46,
'id': [3, 4, 6, 2, 1, 6, 1, 4, 2]}}]
I have a task to get the average some data in each hour inside a week.
{'hour': 0, 'count': 70}
{'hour': 1, 'count': 92}
{'hour': 2, 'count': 94}
{'hour': 3, 'count': 88}
{'hour': 4, 'count': 68}
{'hour': 5, 'count': 69}
{'hour': 6, 'count': 70}
{'hour': 7, 'count': 82}
{'hour': 8, 'count': 91}
{'hour': 9, 'count': 67}
{'hour': 10, 'count': 92}
{'hour': 11, 'count': 100}
{'hour': 12, 'count': 92}
{'hour': 13, 'count': 55}
{'hour': 14, 'count': 61}
{'hour': 15, 'count': 47}
{'hour': 16, 'count': 36}
{'hour': 17, 'count': 19}
{'hour': 18, 'count': 11}
{'hour': 19, 'count': 6}
{'hour': 20, 'count': 3}
{'hour': 21, 'count': 9}
{'hour': 22, 'count': 27}
{'hour': 23, 'count': 47}
The data above is the result of this query
result = Device.objects.filter(station__in=stations, created_at__range=(start_date, end_date)) \
.extra({'hour': 'hour(created_at)'}) \
.values('hour').annotate(count=Count('id')).order_by('hour')
the result is queryed by 7 days range, what I want to do is get the average for each hour in 7 days, exampe the total of count in hour 0 is 70 then i need to average it from 7 days.
Any suggestion?
Probably you can try like this with F() expression:
from django.db.models import F, ExpressionWrapper, DecimalField
result = result.annotate(average=ExpressionWrapper(F('count')/7, output_field=DecimalField()))
I have a list of dicts and would like to design a function to output a new dict which contains the sum for each unique key across all the dicts in the list.
For the list:
[
{
'apples': 1,
'oranges': 1,
'grapes': 2
},
{
'apples': 3,
'oranges': 5,
'grapes': 8
},
{
'apples': 13,
'oranges': 21,
'grapes': 34
}
]
So far so good, this can be done with a counter:
def sumDicts(listToProcess):
c = Counter()
for entry in listToProcess:
c.update(entry)
return (dict(c))
Which correctly returns:
{'apples': 17, 'grapes': 44, 'oranges': 27}
The trouble comes when the dicts in my list start to contain nested dicts:
[
{
'fruits': {
'apples': 1,
'oranges': 1,
'grapes': 2
},
'vegetables': {
'carrots': 6,
'beans': 3,
'peas': 2
},
'grains': 4,
'meats': 1
},
{
'fruits': {
'apples': 3,
'oranges': 5,
'grapes': 8
},
'vegetables': {
'carrots': 7,
'beans': 4,
'peas': 3
},
'grains': 3,
'meats': 2
},
{
'fruits': {
'apples': 13,
'oranges': 21,
'grapes': 34
},
'vegetables': {
'carrots': 8,
'beans': 5,
'peas': 4
},
'grains': 2,
'meats': 3
},
]
Now the same function will give a TypeError because the counter can't add two Dicts.
The desired result would be:
{
'fruits': {
'apples': 17,
'oranges': 27,
'grapes': 44
},
'vegetables': {
'carrots': 21,
'beans': 12,
'peas': 9
},
'grains': 9,
'meats': 6
}
Any ideas on how to do this in a reasonably efficient, Pythonic, generalizable way?
I would do this by performing a recursive merge on a recursively defined collections.defaultdict object.
from collections import defaultdict
def merge(d, new_d):
for k, v in new_d.items():
if isinstance(v, dict):
merge(d[k], v)
else:
d[k] = d.setdefault(k, 0) + v
# https://stackoverflow.com/a/19189356/4909087
nested = lambda: defaultdict(nested)
d = nested()
for subd in data:
merge(d, subd)
Using default_to_regular to convert it back, we have:
default_to_regular(d)
# {
# "fruits": {
# "apples": 17,
# "oranges": 27,
# "grapes": 44
# },
# "vegetables": {
# "carrots": 21,
# "beans": 12,
# "peas": 9
# },
# "grains": 9,
# "meats": 6
# }
You can use recursion. This solution finds all the dictionary keys in the input passed to merge, and then sums the values for each key if the values are integers. If the values are dictionaries, however, merge is called again:
def merge(c):
_keys = {i for b in c for i in b}
return {i:[sum, merge][isinstance(c[0][i], dict)]([h[i] for h in c]) for i in _keys}
d = [{'fruits': {'apples': 1, 'oranges': 1, 'grapes': 2}, 'vegetables': {'carrots': 6, 'beans': 3, 'peas': 2}, 'grains': 4, 'meats': 1}, {'fruits': {'apples': 3, 'oranges': 5, 'grapes': 8}, 'vegetables': {'carrots': 7, 'beans': 4, 'peas': 3}, 'grains': 3, 'meats': 2}, {'fruits': {'apples': 13, 'oranges': 21, 'grapes': 34}, 'vegetables': {'carrots': 8, 'beans': 5, 'peas': 4}, 'grains': 2, 'meats': 3}]
import json
print(json.dumps(merge(d), indent=4))
Output:
{
"meats": 6,
"grains": 9,
"fruits": {
"grapes": 44,
"oranges": 27,
"apples": 17
},
"vegetables": {
"beans": 12,
"peas": 9,
"carrots": 21
}
}
I have a list containing multiple dictionaries. Each dictionary contains exact 7 keys. But, the values of keys is mix of string and integer. I want to add the values of integer one.
Below, is my list of dictionaries: I want to just add the values of vega, theta, delta, gamma from all the three dictionaries.
[{'option_type': 'Call', 'expiry': datetime.datetime(1993, 3, 4, 15, 20, 26), 'vega': 2, 'notional': 7840, 'delta': 1, 'strike': 520, 'theta': 5, 'gamma': 3}, {'option_type': 'Call', 'expiry': datetime.datetime(1995, 11, 14, 10, 25, 50), 'vega': 2, 'notional': 1930, 'delta': 1, 'strike': 1960, 'theta': 5, 'gamma': 3}, {'option_type': 'Put', 'expiry': datetime.datetime(1993, 3, 7, 17, 2, 30), 'vega': 2, 'notional': 5530, 'delta': 1, 'strike': 1520, 'theta': 5, 'gamma': 3}]
Here is one option:
>>> import datetime
>>> data_set = [{'option_type': 'Call', 'expiry': datetime.datetime(1993, 3, 4, 15, 20, 26), 'vega': 2, 'notional': 7840, 'delta': 1, 'strike': 520, 'theta': 5, 'gamma': 3}, {'option_type': 'Call', 'expiry': datetime.datetime(1995, 11, 14, 10, 25, 50), 'vega': 2, 'notional': 1930, 'delta': 1, 'strike': 1960, 'theta': 5, 'gamma': 3}, {'option_type': 'Put', 'expiry': datetime.datetime(1993, 3, 7, 17, 2, 30), 'vega': 2, 'notional': 5530, 'delta': 1, 'strike': 1520, 'theta': 5, 'gamma': 3}]
>>>
>>> counts = {'vega': 0, 'theta': 0, 'delta': 0, 'gamma': 0}
>>>
>>> for data in data_set:
... for key in counts.keys():
... counts[key] += data[key]
...
>>>
>>> counts
{'gamma': 9, 'vega': 6, 'delta': 3, 'theta': 15}
Simply iterate and use sum() method
sum_vega = sum(i['vega'] for i in give_dict)
sum_theta = sum(i['theta'] for i in give_dict)
sum_delta = sum(i['delta'] for i in give_dict)
sum_gamma = sum(i['gamma'] for i in give_dict)
Use this:
import datetime
my_list=[
{
"vega": 2,
"notional": 7840,
"delta": 1,
"strike": 520,
"theta": 5,
"option_type": "Call",
"gamma": 3,
"expiry": datetime.datetime(1993, 3, 4, 15, 20, 26)
},
{
"vega": 2,
"notional": 1930,
"delta": 1,
"strike": 1960,
"theta": 5,
"option_type": "Call",
"gamma": 3,
"expiry": datetime.datetime(1995, 11, 14, 10, 25, 50)
},
{
"vega": 2,
"notional": 5530,
"delta": 1,
"strike": 1520,
"theta": 5,
"option_type": "Put",
"gamma": 3,
"expiry": datetime.datetime(1993, 3, 7, 17, 2, 30)
}
]
result = {}
for dict_ in my_list:
for key in dict_:
if result.has_key(key):
if isinstance(dict_[key], int):# For integers
result[key] += dict_[key]
#if isinstance(dict_[key], str):# For strings
# result[key] = result[key] + '' + dict_[key]
# We do not sum other types
else:
result[key] = dict_[key]
print result
Well if you already know the keys whose values you want to add, you can simply create a lookup list while iterating through the items and adding them.
Something along these lines:
lookup_count_list = {'vega':0, 'theta':0, 'delta':0, 'gamma':0}
dict_list = [{'option_type': 'Call', 'expiry': datetime.datetime(1993, 3, 4, 15, 20, 26), 'vega': 2, 'notional': 7840, 'delta': 1, 'strike': 520, 'theta': 5, 'gamma': 3}, {'option_type': 'Call', 'expiry': datetime.datetime(1995, 11, 14, 10, 25, 50), 'vega': 2, 'notional': 1930, 'delta': 1, 'strike': 1960, 'theta': 5, 'gamma': 3}, {'option_type': 'Put', 'expiry': datetime.datetime(1993, 3, 7, 17, 2, 30), 'vega': 2, 'notional': 5530, 'delta': 1, 'strike': 1520, 'theta': 5, 'gamma': 3}]
for item in dict_list:
for key, value in item.iteritems():
if key in lookup_count_list.keys():
item[key] += 1
print(lookup_count_list)