Python Forum
List of dictionaries: use key-value instead of index?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List of dictionaries: use key-value instead of index?
#5
colors = [
    {'colorkey': 'red', 'status': 'on', 'registered': 'yes'},
    {'colorkey': 'blue', 'status': 'off', 'registered': 'no'},
    {'colorkey': 'green', 'status': 'on', 'registered': 'yes'},
    ]

color_to_find = 'red'
for element in colors:
    # element is a dict
    color = element.get('colorcode')
    if color == color_to_find:
        # result found
        # stop the iteration if you want to have only one result.
        # otherwise you must walk through the complete list
        # if you break out of the lopp
        # you'll only get the first hit
        break
else:
    pass
    # result not found, for loop finished completely
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: List of dictionaries: use key-value instead of index? - by DeaD_EyE - Jun-03-2019, 05:28 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Sort a list of dictionaries by the only dictionary key Calab 1 504 Oct-27-2023, 03:03 PM
Last Post: buran
  Access list of dictionaries britesc 4 1,091 Jul-26-2023, 05:00 AM
Last Post: Pedroski55
Thumbs Down I hate "List index out of range" Melen 20 3,354 May-14-2023, 06:43 AM
Last Post: deanhystad
  IndexError: list index out of range dolac 4 1,925 Jul-25-2022, 03:42 PM
Last Post: deanhystad
  IndexError: list index out of range Anldra12 2 1,449 May-03-2022, 01:39 PM
Last Post: Anldra12
  IndexError: list index out of range rf_kartal 6 2,863 Sep-07-2021, 02:36 PM
Last Post: Larz60+
  Python Error List Index Out of Range abhi1vaishnav 3 2,326 Sep-03-2021, 08:40 PM
Last Post: abhi1vaishnav
  IndexError: list index out of range Laplace12 1 2,233 Jun-22-2021, 10:47 AM
Last Post: Yoriz
  function that returns a list of dictionaries nostradamus64 2 1,765 May-06-2021, 09:58 PM
Last Post: nostradamus64
  IndexError: list index out of range brunolelli 11 6,579 Mar-25-2021, 11:36 PM
Last Post: brunolelli

Forum Jump:

User Panel Messages

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