Python Forum
update values in list based on dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
update values in list based on dictionary
#4
Another possibility is to be creative with indexing without need to convert dictionary.

'Get index of needed value in list of dictionary values and find key with same index in list of dictionary keys':

>>> d = {1: 'ham', 2: 'eggs', 3: 'bacon'}
>>> value = 'eggs'
>>> [*d.keys()][[*d.values()].index(value)]    # instead of *d.keys() one may use *d
2
This way it is possible to have non-hashable values but still find corresponding key:

>>> d = {1: ['ham'], 2: ['eggs'], 3: ['bacon']}                             
>>> value = ['bacon']                                                       
>>> [*d.keys()][[*d.values()].index(value)]                         
3
NB! If there are several equal values this will return first one encountered.

Follow-up edit: so one can utilize this something like following:

>>> dct = {'1': 'one', '2': 'two', '3': 'three'}
>>> lst = [
...       ['one', 'uno'],
...       ['two', 'dos'],
...       ['three', 'tres']
... ]
>>> for row in lst:
...     row[0] = [*dct][[*dct.values()].index(row[0])]
...
>>> lst
[['1', 'uno'], ['2', 'dos'], ['3', 'tres']]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
RE: update values in list based on dictionary - by perfringo - Jun-10-2019, 07:26 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question Using Lists as Dictionary Values bfallert 8 344 Apr-21-2024, 06:55 AM
Last Post: Pedroski55
  unable to remove all elements from list based on a condition sg_python 3 453 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  Dictionary in a list bashage 2 561 Dec-27-2023, 04:04 PM
Last Post: deanhystad
  filtering a list of dictionary as per given criteria jss 5 696 Dec-23-2023, 08:47 AM
Last Post: Gribouillis
  need to compare 2 values in a nested dictionary jss 2 872 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  Copying the order of another list with identical values gohanhango 7 1,169 Nov-29-2023, 09:17 PM
Last Post: Pedroski55
  Search Excel File with a list of values huzzug 4 1,260 Nov-03-2023, 05:35 PM
Last Post: huzzug
  Sort a list of dictionaries by the only dictionary key Calab 1 497 Oct-27-2023, 03:03 PM
Last Post: buran
  Comparing List values to get indexes Edward_ 7 1,179 Jun-09-2023, 04:57 PM
Last Post: deanhystad
  Printing specific values out from a dictionary mcoliver88 6 1,422 Apr-12-2023, 08:10 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020