0

i have a list of dictionary as below:

benefits = [{'BENEFITS': 'DEATH', 'name of benefits': 'abcxyz'}, {'BENEFITS': 'DEATH', 'name of benefits': 'qwerty'}]

i would like to get a value of 'BENEFITS' if the value of 'name of benefits' = 'abcxyz'.. Could you please assist on this ?

for i in benefits:
    for k,v in i.items():
        if v == "abcxyz":
            print(v)

the expected output is if v == "abcxyz" , output is 'DEATH'

van thang
  • 99
  • 2
  • 9
  • Does this answer your question? [How can I extract all values from a dictionary in Python?](https://stackoverflow.com/questions/7002429/how-can-i-extract-all-values-from-a-dictionary-in-python) – nathan liang Mar 15 '22 at 02:09

4 Answers4

0

This should work:

benefits = [{'BENEFITS': 'DEATH', 'name of benefits': 'abcxyz'}, {'BENEFITS': 'DEATH', 'name of benefits': 'qwerty'}]
for i in benefits:
    for k,v in i.items():
        if v == "abcxyz":
            print(i['BENEFITS'])

Output:

DEATH

What you did wrong is that you printed v if v == "abcxyz". You need to print the value of BENEFITS instead which is what I changed.

catasaurus
  • 933
  • 4
  • 20
0

You don't need for loop there. Just grab the items directly:

for d in benefits: 
    if d["name of benefits"] == "abcxyz":
        print(d["BENEFITS"])

Note that if you just check if v=="abcxyz", it will check any value is "abcxyz", regardless of any key.

Chris
  • 29,127
  • 3
  • 28
  • 51
0

You could just expand a list comprehension into print and specify sep and end arguments to print.

benefits = [{'BENEFITS': 'DEATH', 'name of benefits': 'abcxyz'},
            {'BENEFITS': 'DEATH', 'name of benefits': 'qwerty'}]

print(*[d['BENEFITS'] for d in benefits if d['name of benefits'] == 'abcxyz'], sep=',', end='\n')

This cleanly handles the possibility of multiple dictionaries in the benefits list having the required 'name of benefits' value.

Chris
  • 26,361
  • 5
  • 21
  • 42
0

You can also use the one line below.

mylist = [d['BENEFITS'] for d in benefits if d['name of benefits'] == 'abcxyz']

Note that it will give you a list of strings (even if there is only one string).

Example:

benefits = [{'BENEFITS': 'DEATH', 'name of benefits': 'abcxyz'}, {'BENEFITS': 'DEATH', 'name of benefits': 'qwerty'},
            {'BENEFITS': 'LIFE', 'name of benefits': 'abcxyz'}]
mylist = [d['BENEFITS'] for d in benefits if d['name of benefits'] == 'abcxyz']
print(mylist)
# This will give you: ['DEATH', 'LIFE']
maxhaz
  • 380
  • 1
  • 2
  • 8