I have a dictionary with multiple keys, and multiple values per key (sometimes). The dictionary is zipped from two lists which I've pulled from an excel sheet using pandas. I've converted the values to integers. My dictionary looks like this:
dictionary = {'A223':[1,4,5],'B224':[7,8,9],'A323':[4,5],'B456':[3,3,4,5] }
What I need now is to modify the dictionary so that each Key only shows the min value. So desired output would look like this:
dictionary = {'A223':1,'B224':7,'A323':4,'B456':3}
I can return the key with the lowest value, however this doesn't help me.
Here is my code thus far:
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)
My steps thus far: 1 - read excel into df with the two columns I need 2 - Convert string values in values column into int. 3 - Create a list for values column, dropping na 4 - zipping together keys and values, customizing a dictionary to accept multiple values per key.
I'm new, and really at a loss here. Any help would be very much appreciated!
I have tried something like:
dictionary = {'A223':[1,4,5],'B224':[7,8,9,],'A323':[4,5],'B456':[3,3,4,5] }
min(dictionary, key=dictionary.get)
Although this only, and obviously, returns the key with the lowest value.
CodePudding user response:
To keep it in the spirit of python one-liners:
>>> 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}
CodePudding user response:
Alternatively comprehension could be used:
newdic = {key: min(value) for key, value in dictionary.items()}