1

I have the following dictionary where the keys are 'month,country:ID' and values are just totals:

ID_dict = {'11,United Kingdom:14416': 129.22, '11,United Kingdom:17001': 357.6, 
'12,United States:14035': 90000.0, '12,United Kingdom:17850': 241.16,'12,United 
States:14099': 90000.0, '12,France:12583': 252.0, '12,United Kingdom:13047': 
215.13, '01,Germany:12662': 78.0, '01,Germany:12600': 14000}

The actual dictionary will be much larger than this one.

I am trying to return the key for each 'month, country' that contains the highest total. If there is a tie the ID's would be separated by a comma. Example Output based on dictionary above:

'11,United Kingdom:17001'
'12,United Kingdom:17850'
'12,United States:14035, 14099'
'12,France:12583'
'01,Germany:12600'

I can get the strings of the highest values using the following code:

highest = max(ID_dict.values())
print([k for k, v in ID_dict.items() if v == highest])

But really struggling to get past this point. I was experimenting using re.match and re.search but was not getting very far with those.

3
  • Wouldn't it be easier to use nested dictionaries, rather than combined keys like this?
    – Barmar
    Sep 22, 2018 at 20:02
  • @Barmar I agree, I wonder if OP would mind restructuring the dict or his data is already setup in this format, he said the actual dict is much larger Sep 23, 2018 at 15:03
  • @bazingaa this is a good one , if you don't change his setup, I got a good way through it but put it on pause, you should try Sep 23, 2018 at 17:08

2 Answers 2

0

You can find the maximum for each month, country pair, store this relation in a dictionary. Then create a dictionary that have as keys the pairs (month, country) and as values a list of IDs that have value equal to the maximum for that (month, country) pair:

import re

ID_dict = {'11,United Kingdom:14416': 129.22, '11,United Kingdom:17001': 357.6,
           '12,United States:14035': 90000.0, '12,United Kingdom:17850': 241.16, '12,United States:14099': 90000.0,
           '12,France:12583': 252.0, '12,United Kingdom:13047': 215.13, '01,Germany:12662': 78.0,
           '01,Germany:12600': 14000}

table = {tuple(re.split(',|:', key)[:2]): value for key, value in sorted(ID_dict.items(), key=lambda e: e[1])}

result = {}
for key, value in ID_dict.items():
    splits = re.split(',|:', key)
    if value == table[tuple(splits[:2])]:
        result.setdefault(tuple(splits[:2]), []).append(splits[2])

for key, value in result.items():
    print('{}:{}'.format(','.join(key), ', '.join(value)))

Output

01,Germany:12600
12,United States:14099, 14035
12,United Kingdom:17850
11,United Kingdom:17001
12,France:12583

The above approach is O(nlogn) because it uses sorted, to make it O(n) you can change the dictionary comprehension by this loop:

table = {}
for s, v in ID_dict.items():
    key = tuple(re.split(',|:', s)[:2])
    table[key] = max(table.get(key, v), v)
0

The following code creates a new dictionary with 'month,country' keys and lists of (value, IDnum) as the values. It then sorts each list, and collects all the IDnums that correspond to the highest value.

ID_dict = {
    '11,United Kingdom:14416': 129.22, '11,United Kingdom:17001': 357.6, 
    '12,United States:14035': 90000.0, '12,United Kingdom:17850': 241.16,
    '12,United States:14099': 90000.0, '12,France:12583': 252.0, 
    '12,United Kingdom:13047': 215.13, '01,Germany:12662': 78.0, 
    '01,Germany:12600': 14000
}

# Create a new dict with 'month,country' keys 
# and lists of (value, IDnum) as the values
new_data = {}
for key, val in ID_dict.items():
    newkey, idnum = key.split(':')
    new_data.setdefault(newkey, []).append((val, idnum))

# Sort the values for each 'month,country' key,
# and get the IDnums corresponding to the highest values
for key, val in new_data.items():
    val = sorted(val, reverse=True)
    highest = val[0][0]
    # Collect all IDnums that have the highest value
    ids = []
    for v, idnum in val:
        if v != highest:
            break
        ids.append(idnum)
    print(key + ':' + ', '.join(ids))

output

11,United Kingdom:17001
12,United States:14099, 14035
12,United Kingdom:17850
12,France:12583
01,Germany:12600
1
  • Haha Very nice II'm jealous, have to get used to using setdefault I knew it had to be used here, was googling how to implement it last night before bed because I wanted to solve this and couldn't get it out of my head but your answers and links helped way more Sep 23, 2018 at 19:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.