Zaheer Jan Zaheer Jan - 3 months ago 8
Python Question

Create dictionary from another dictionary with the fastest and scalable way

I have few scenarios to create a new dictionary:


  1. only take those dictionary in list with key 'total' is not zero

  2. delete keys from dictionary e.g 'total' and 'rank'

  3. use the 'name' key value as key and 'game' key value as list of

    values in the new dict

  4. sort the list of values in new dict



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?

Answer

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.