简体   繁体   中英

I have a dictionary with lists of values. I want to take the highest value from the list of values

suppose I have a dictionary

y = {'town1': ['moderate', 'low'], 'town2': ['high'], 'town3': ['moderate', 'severe']}

I want the dictionary to only have one value rather than a list and take the highest risk value. So for town 1 highest risk is moderate, for town 2 it's high and for town 3 its severe The order of risk is ( 'severe','high','moderate', low)

desired output: y = {'town1': ['moderate'], 'town2': ['high'], 'town3': ['severe']}

My code is below:

x = []
for k,v in y.items():
    x.append((k,v))

print(x)
for key, value in y.items():
    for i in range(len(x)):
        if 'severe' in x[i][1]:
            y[key] = 'severe'
        elif 'high' in x[i][1]:
            y[key] = ['high']
        elif 'moderate' in x[i][1]:
            y[key] = ['moderate']
        elif 'low' in x[i][1]:
            y[key] = ['low']

print(y)

You don't have to iterate explicitly over the severity lists, the in operator is doing this for you:

x = {'town1': ['moderate', 'low'], 'town2': ['high'], 'town3': ['moderate', 'severe']}
print(x)

y = {}
for key, values in x.items():
    if 'severe' in values:
        y[key] = ['severe']
    elif 'high' in values:
        y[key] = ['high']
    elif 'moderate' in values:
        y[key] = ['moderate']
    elif 'low' in values:
        y[key] = ['low']

print(y)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM