python字典中部分匹配键的最大值 [英] Max values for partial matching keys in python dictionary
问题描述
我有以下字典,其中键是月份,国家:ID",值只是总数:
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.
我试图返回包含最高总数的每个月份、国家/地区"的密钥.如果有平局,ID 将用逗号分隔.基于上述字典的示例输出:
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])
但真的很难通过这一点.我曾尝试使用 re.match 和 re.search,但并没有取得太大进展.
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.
推荐答案
以下代码创建了一个新字典,其中包含 'month,country' 键和 (value, IDnum) 列表作为值.然后对每个列表进行排序,并收集与最高值对应的所有 IDnum.
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))
输出
11,United Kingdom:17001
12,United States:14099, 14035
12,United Kingdom:17850
12,France:12583
01,Germany:12600
这篇关于python字典中部分匹配键的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!