[英]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']} y = {'town1':['中等','低'],'town2':['高'],'town3':['中等','严重']}
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)因此,对于城镇 1 的最高风险是中等的,对于城镇 2 的风险很高,对于城镇 3 的风险是严重的。风险的顺序是('严重','高','中等',低)
desired output: y = {'town1': ['moderate'], 'town2': ['high'], 'town3': ['severe']}所需的 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:您不必显式地遍历严重性列表, in
运算符正在为您执行此操作:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.