Doof
Doof

Reputation: 143

Selecting the max value from 2 dictionaries

I have 2 dictionaries d1 and d2 as shown below:

enter image description here

(I have a data frame where the columns contain dictionaries, Ive taken one value from it)

what I want to do is, compare these d1 and d2, get the common cities(d1 intersection d2) and see in d1 to find the city with the maximum value. If there is a tie between 2 or more cities in d1, then I plan on checking d2 values as tie breaker.

Even though I have this idea, I am not sure how to code it in an efficient manner since the data frame is about 100000 rows .I would like the code to take as minimum time as possible for execution. How would I achieve this?

In response to comment of @Joshua, I am putting the dictionary as text:

d1:
{'Bangalore': 50.0, 'Vadakara': 6.25, 'Pathanapuram': 6.25, 'Kannur': 6.25, 'Adoor': 3.125, 'Kozhikode': 7.8125, 'Pathanamthitta': 4.6875, 'Thalassery': 1.5625, 'Coimbatore': 1.5625, 'Calicut': 6.25, 'Kanjanagadu': 3.125, 'Chennai': 1.5625, 'Perambra': 1.5625}

d2:
{'Bangalore': 45.0, 'Kozhikode': 28.333333333333332, 'Thrissur District': 21.666666666666668, 'Kannur': 3.3333333333333335, 'Wayanad': 1.6666666666666667}

Upvotes: 1

Views: 620

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195543

You can use max() with custom key=:

d1 = {
    "Bangalore": 50.0,
    "Vadakara": 6.25,
    "Pathanapuram": 6.25,
    "Kannur": 6.25,
    "Adoor": 3.125,
    "Kozhikode": 7.8125,
    "Pathanamthitta": 4.6875,
    "Thalassery": 1.5625,
    "Coimbatore": 1.5625,
    "Calicut": 6.25,
    "Kanjanagadu": 3.125,
    "Chennai": 1.5625,
    "Perambra": 1.5625,
}

d2 = {
    "Bangalore": 45.0,
    "Kozhikode": 28.333333333333332,
    "Thrissur District": 21.666666666666668,
    "Kannur": 3.3333333333333335,
    "Wayanad": 1.6666666666666667,
}

city = max(d1.keys() & d2.keys(), key=lambda k: (d1[k], d2[k]))
print(city)

Prints:

Bangalore

Upvotes: 4

Related Questions