I have few scenarios to create a new dictionary:
My code is:
# input dictionary
data =[
{'name': 'foo', 'rank': 3, 'game': 'football', 'total': 1},
{'name': 'bar', 'rank': 5, 'game': 'hockey', 'total': 0},
{'name': 'foo', 'rank': 7, 'game': 'tennis', 'total': 0},
{'name': 'foo', 'rank': 2, 'game': 'cricket', 'total': 2},
{'name': 'bar', 'rank': 1, 'game': 'cricket', 'total': 8},
]
result_list = []
merged_data = {}
result_data = {}
# Get the list of dict if key 'total' value is not zero
dict_without_total = [
den for den in data if den.get('total')
]
for my_dict in dict_without_total:
# deleting key 'brand' and 'total' from the
del my_dict['rank']
del my_dict['total']
result_data.update({
my_dict.get('name'): (my_dict.get('game'))
})
result_list.append(result_data)
# store all values of same keys in list and sort the values list
for result in result_list:
for keys, values in result.items():
if keys not in merged_data:
merged_data[keys] = []
merged_data[keys].append(values)
merged_data[keys].sort()
print merged_data
Output of my code:
{
'bar': ['cricket', 'cricket', 'cricket'],
'foo': ['cricket', 'cricket', 'cricket']
}
Expected result:
{
'foo': ['cricket', 'football'],
'bar': ['cricket']
}
Is there a faster way to get the result, or can I use some python builtin function to handle this scenario?
You could really simplify this as there is no need to modify the existing dictionary. It's usually a lot cleaner to leave the original data structure alone and build a new one as the result.
data = [
{'name': 'foo', 'rank': 3, 'game': 'football', 'total': 1},
{'name': 'bar', 'rank': 5, 'game': 'hockey', 'total': 0},
{'name': 'foo', 'rank': 7, 'game': 'tennis', 'total': 0},
{'name': 'foo', 'rank': 2, 'game': 'cricket', 'total': 2},
{'name': 'bar', 'rank': 1, 'game': 'cricket', 'total': 8},
]
result = {}
for e in data:
if e["total"]:
name = e["name"]
if name not in result:
result[name] = []
result[name].append(e["game"])
print result
The result is {'foo': ['football', 'cricket'], 'bar': ['cricket']}
which is what you're looking for.
You can try:
data =[
{'name': 'foo', 'rank': 3, 'game': 'football', 'total': 1},
{'name': 'bar', 'rank': 5, 'game': 'hockey', 'total': 0},
{'name': 'foo', 'rank': 7, 'game': 'tennis', 'total': 0},
{'name': 'foo', 'rank': 2, 'game': 'cricket', 'total': 2},
{'name': 'bar', 'rank': 1, 'game': 'cricket', 'total': 8},
]
final_dict={}
for single_data in data:
if single_data['total'] > 0:
if single_data['name'] in final_dict:
final_dict[single_data['name']].append(single_data['game'])
else:
final_dict[single_data['name']]=[single_data['game']]
print final_dict
Output:
{'foo': ['football', 'cricket'], 'bar': ['cricket']}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With