Home > Mobile >  Getting all values from dictionary with specific key element
Getting all values from dictionary with specific key element

Time:03-22

I have a dictionary in Python with 4 elements of the key (2 strings, 2 ints) and one numerical value. How do I return key-value pairs that have a specific value for one element of the key? For example, if my dictionary is newdict:

newdict = {('1', '14', 3, 1): 3.469446951953614e-18,
     ('1', '14', 11, 1): 1.1102230246251565e-15,
     ('1', '17', 2, 1): 171.3624841,
     ('1', '21', 5, 1): -1.6764367671839864e-14,
     ('1', '21', 11, 1): 5.551115123125783e-17,
     ('1', '23', 8, 1): -4.163336342344337e-15,
     ('1', '24', 9, 1): -8.36136715420821e-15,
     ('1', '25', 5, 1): 0.0221293,
     ('1', '25', 9, 1): 0.0327717}

How would I return only the key-value pairs that have 5 as their third element, for example:

{('1', '21', 5, 1): -1.6764367671839864e-14,
    ('1', '25', 5, 1): 0.0221293}

CodePudding user response:

You can use a dictionary comprehension:

{key: value for key, value in newdict.items() if key[2] == 5}

This outputs:

{('1', '21', 5, 1): -1.6764367671839864e-14, ('1', '25', 5, 1): 0.0221293}

CodePudding user response:

How do I return key-value pairs that have a specific value for one element of the key?

  • Write a function that takes position, value, and item parameters
    • Test the key portion of the item for the position and value
    • return a boolean for the test/comparison
  • Filter the dictionary items using that function.
  • Related