繁体   English   中英

在每个键有多个值的字典中查找每个键的最低值

[英]Finding the lowest value per key in a dictionary with multiple values per key

我有一个包含多个键的字典,每个键有多个值(有时)。 这本字典是从我使用 pandas 从 excel 工作表中提取的两个列表压缩而来的。我已将值转换为整数。 我的字典看起来像这样:

dictionary = {'A223':[1,4,5],'B224':[7,8,9],'A323':[4,5],'B456':[3,3,4,5] }

我现在需要的是修改字典,让每个Key只显示最小值。 所以想要的 output 看起来像这样:

dictionary = {'A223':1,'B224':7,'A323':4,'B456':3}

我可以返回具有最低值的密钥,但这对我没有帮助。

到目前为止,这是我的代码:

df = pd.read_excel(PT, sheet_name= "Permit Tracker")

permit_list = ['1.Planning', '2.Survey Complete', '3.Design Complete', '4.Permit Submitted', '5.Permit Approved','6.IFC', '7.As-Built', '8.On-Hold', '9.Cancelled'] #original values column, to be converted to int.

dicto = {
    '1.Planning': 1, '2.Survey Complete': 2, '3.Design Complete': 3, '4.Permit Submitted': 4, '5.Permit Approved': 5,
    '6.IFC': 6, '7.As-Built': 7, '8.On-Hold': 8, '9.Cancelled': 9
    }

new_int = [dicto[k] for k in permit_list]
dfint = df['Permit Status'].dropna().tolist()
dfkeys = df['RPATS#'] #this is the keys column in my excel sheet

new_conversion = [dicto[k] for k in dfint]

dictionary = {}
for i, j in zip(dfkeys,new_conversion):
    dictionary.setdefault(i, []).append(j)

print(dictionary)

到目前为止我的步骤: 1 - 使用我需要的两列将 excel 读入 df 2 - 将值列中的字符串值转换为 int。 3 - 为值列创建一个列表,删除 na 4 - 将键和值压缩在一起,自定义字典以接受每个键的多个值。

我是新手,在这里真的很茫然。 任何帮助将不胜感激!

我试过类似的东西:

dictionary = {'A223':[1,4,5],'B224':[7,8,9,],'A323':[4,5],'B456':[3,3,4,5] }
min(dictionary, key=dictionary.get)

虽然这只是,而且很明显,返回具有最低值的键。

为了保持 python 一行的精神:

>>> dictionary
{'A223': [1, 4, 5], 'B224': [7, 8, 9], 'A323': [4, 5], 'B456': [3, 3, 4, 5]}
>>> dict(map(lambda x: (x[0], min(x[1])), dictionary.items()))
{'A223': 1, 'B224': 7, 'A323': 4, 'B456': 3}

或者可以使用理解:

newdic = {key: min(value) for key, value in dictionary.items()}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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