I have been trying to figure out how to return the key which has the nth biggest value in a nested dictionary. What causes problems for me is if there's some missing values like
my_dict = {'0': {'name': 'A', 'price': 50}, '1': {'name': 'B', 'price': 20}, '2': {'name': 'C'}, '3': {'name': 'D', 'price': 10}}
If every price existed, I could use code such as this to get the correct key:
sorted_list = sorted(my_dict.items(), key=lambda item: item[1]['price'])
print(sorted_list[-number_im_using_to_find][1]['name'])
How to account for missing values in an efficient way?
CodePudding user response:
you can use dict.get
to achieve this:
get(key[, default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
Here is a code implementation using dict.get
:
default_value = -1
key = lambda item: item[1].get('price', default_value)
sorted_list = sorted(my_dict.items(), key=key)
If you want just sorted values you could remove entirely the index [1]
:
default_value = -1
key = lambda value: value.get('price', default_value)
sorted_list = sorted(my_dict.values(), key=key)
EDIT: if you want to be sortable with NoneType
in the list, you could use something like:
>>> mylist = [3, 1, None, None, 2, 0]
>>> mylist.sort(key=lambda x: x or -1)
>>> mylist
[None, None, 0, 1, 2, 3]
CodePudding user response:
Use get
with a default value, in this case 0 or even a negative value to put the elements with missing prices all the way down the sorted list.
lambda item: item[1].get('price', 0)