get maximum valued dictionary from list of dictionaries in python - python

I have this list.
dict_list = [{"rp":1,"vi":100},{"rp":2,"vi":70},{"rp":1,"vi":200},{"rp":1,"vi":150},{"rp":2,"vi":300},{"rp":3, "vi":120 }]
I want output as:
[ {"rp":1,"vi":200},{"rp":2,"vi":300},{"rp":3,"vi":120}]
Can anyone help??

You can build a temporary dictionary using the 'rp' values as keys and feeding the data in order of 'vi' value to retain the highest 'vi' value for each unique 'rp' key. Then convert the values of that temporary dictionary into a list of dictionaries:
R = [*{d["rp"]:d for d in sorted(dict_list,key=lambda d:d["vi"])}.values()]
print(R)
[{'rp': 2, 'vi': 300}, {'rp': 1, 'vi': 200}, {'rp': 3, 'vi': 120}]

One solution could be to create a dictionary with key as the rp value and value as the maximum vi value.
Use the created dictionary to create the required list
dict_list = [{"rp":1,"vi":100},{"rp":2,"vi":70},{"rp":1,"vi":200},{"rp":1,"vi":150},{"rp":2,"vi":300},{"rp":3, "vi":120 }]
res = dict()
for elt in dict_list:
res[elt["rp"]] = max(res.get(elt["rp"], 0), elt["vi"]) # overwrite with max for matching keys
dict_list = [{"rp": key, "vi": value} for key, value in res.items()]
print(dict_list)

I am not sure if this is the most elegant way to do it but I hope it helps.
you can try to use pandas for something like this:
import pandas as pd
dict_list = [{"rp":1,"vi":100},{"rp":2,"vi":70},{"rp":1,"vi":200},
{"rp":1,"vi":150},{"rp":2,"vi":300},{"rp":3, "vi":120 }]
full = pd.DataFrame(dict_list)
rp_list = pd.Series(full['rp']).unique()
new= []
for rp in rp_list:
values = full.loc[full['rp'] == rp]
max_value = values["vi"].max()
new.append({'rp':rp,'vi':max_value})
print (new)

Related

Merge multiple key in dictionary with same values inside an array

I need to merge three dictionaries with array values into a single dict based on if they have same values inside the array. The dictionaries is like this:
data = {
'A1':['Cheese','Cupcake', 'Salad','Sandwich'],
'A2':['Cheese','Cupcake', 'Pasta','Pudding'],
'A3':['Pudding','Pasta', 'Salad','Sandwich']
}
Then, the output would be like this:
{
'A1,A2':['Cheese','Cupcake']
'A1,A3':['Salad', 'Sandwich']
'A2,A3':['Pudding','Pasta']
}
I've tried this:
tmp = {}
for key, value in data.items():
if value in tmp:
tmp[value].append(key)
else:
tmp[value] = [ key ]
print(tmp)
But it only works if the values isn't a list or array. Any solution?
Given you use case, you could use itertools.combinations and set intersection:
data = {
'A1':['Cheese','Cupcake', 'Salad','Sandwich'],
'A2':['Cheese','Cupcake', 'Pasta','Pudding'],
'A3':['Pudding','Pasta', 'Salad','Sandwich']
}
from itertools import combinations
out = {f'{a},{b}': list(set(data[a]).intersection(data[b]))
for a,b in combinations(data, 2)}
output:
{'A1,A2': ['Cupcake', 'Cheese'],
'A1,A3': ['Sandwich', 'Salad'],
'A2,A3': ['Pasta', 'Pudding']}

apply a function on list values from dictionary and make a new dictionary

I have a dictionary where values are in shape of a list.
entities = {"CAMERA": ["camera"], "DISPLAY": ["display", "bild"], "AKKU": ["akku", "battery"]}
I want to iterate through all items in each list and apply a function to each of those items. Then I want to add the resulting values to my new_dict such that
new_dict = {"CAMERA": [0.1], "DISPLAY": [0.55, 0.2]}
where 0.55 and 0.22 are values returned by myFunctionfor each item in the list.
def checkValue(value):
new_dict = {}
#for key, value in entities:
result = myFunction((key), (value))
new_dict[i] = result
How can I do so in a readable manner?
Without having the opportunity to test your full code, I would say:
def checkValue(value):
new_dict = {}
for key, values in entities.items():
new_dict[key] = []
for value in values:
result = myFunction(key, value)
new_dict[key].append(result)
#or directly new_dict[key].append(myFunction(key, value))

How do I create a list inside python dictionary having key and key variable?

I have an empty dictionary. I add key and key variable to that dictionary. How do I create an empty list having key and key variable?
result = {}
result['key'] = 20
print(result)= {'key': 20}
result['key'] = []
result2 = {}
result['key'].append(result2)
Expected result : {'key':20 : [{'7219': '0.49954929481682875'}, {'1416': '0.48741579334133667'}
But it comes like,
{'key': [{'7219': '0.49954929481682875'}, {'1416': '0.48741579334133667'}]
Looks like you need.
result = {}
result['key'] = {20: []}
print(result) # --> {'key': {20: []}}
result2 = {}
result['key'][20].append(result2)
print(result)
As far as I understand your question, you do not necessarily want to save the value "20" with the key "key", but rather use "20" as the key. In order to achieve that, your code should look like the following (careful, this basically spells out every step):
# save an empty list using the key int(20)
# define the key and an empty dictionary
my_key = 20
result = {}
# use the key variable as key for the dictionary and create an empty list there
result[my_key] = []
# now add the other result dictionary to this list
result2 = {
#... some entries
}
result[my_key].append(result2)
# ... some more code
This finally results in a dictionary in this form:
{20 : [{'7219': '0.49954929481682875'}, {'1416': '0.48741579334133667'}]}
However, this is only my interpretation of your issue. If I got something wrong, just ping me up.

How can I add the value if there are duplicate record in a list of dictionaries?

I've tried other solutions but still have no luck, My problem is that I have a list of dictionaries in which I have to check if there are any duplicate value in the key (name of the person):
Sample list:
[{"id": 1,"name": "jack","count": 7},{"id": 12,"name": "jack","count": 5}]
If there are duplicate names, It should add the value in the key count, and the result should be:
[{"id": 1,"name": "jack","count": 12}]
Edited: ID's don't matter, I need at least one id to appear.
A detailed solution could be that:
new = {}
for d in data:
name = d["name"]
if name in new:
new[name]["count"] += d["count"]
else:
new[name] = dict(d)
result = list(new.values())
NB: this could be simplified with the use of list comprehension and the method get, but I think this one is the more readable.
As id field is not so important I will create a dict with key as name and value being the item values in a list
from collections import defaultdict
a = [{"id": 1,"name": "jack","count": 7},{"id": 12,"name": "jack","count": 5}]
d = defaultdict(list)
Iterate over the list and map key and values
for idx,i in enumerate(a):
d[i['name']].append(i) #key is 'name'
At this point d will look like this
{'jack': [{'count': 7, 'id': 1, 'name': 'jack'},{'count': 5, 'id': 12,
'name': 'jack'}]}
Now if the length of list is >1 means we have to iterate over the list and do the summation and update the count
for k,v in d.items():
if len(v) > 1:
temp = v[0]
for t in v[1:]:
temp['count'] = temp['count']+t['count'] #update the count
d[k] = temp
print(list(d.values())) #[{'count': 12, 'id': 1, 'name': 'jack'}]
In order to handle the case when count is missing like
[{"id": 1,"name": "jack"},{"id": 12,"name": "jack","count": 5}]
replace above count update logic with
temp['count']=temp.get('count',0)+t.get('count',0)

Python - Splitting dictionary into dictionaries with the same values?

Say I have a dictionary with many items that have the same values; for example:
dict = {'hello':'a', 'goodbye':'z', 'bonjour':'a', 'au revoir':'z', 'how are you':'m'}
How would I split the dictionary into dictionaries (in this case, three dictionaries) with the same values? In the example, I want to end up with this:
dict1 = {'hello':'a', 'bonjour':'a'}
dict2 = {'goodbye':'z', 'au revoir':'z'}
dict3 = {'how are you':'m'}
You can use itertools.groupby to collect by the common values, then create dict objects for each group within a list comprehension.
>>> from itertools import groupby
>>> import operator
>>> by_value = operator.itemgetter(1)
>>> [dict(g) for k, g in groupby(sorted(d.items(), key = by_value), by_value)]
[{'hello': 'a', 'bonjour': 'a'},
{'how are you': 'm'},
{'goodbye': 'z', 'au revoir': 'z'}]
Another way without importing any modules is as follows:
def split_dict(d):
unique_vals = list(set(d.values()))
split_dicts = []
for i in range(len(unique_vals)):
unique_dict = {}
for key in d:
if d[key] == unique_vals[i]:
unique_dict[key] = d[key]
split_dicts.append(unique_dict)
return split_dicts
For each unique value in the input dictionary, we create a dictionary and add the key values pairs from the input dictionary where the value is equal to that value. We then append each dictionary to a list, which is finally returned.

Categories