V. I
V. I

Reputation: 45

How to iterate over a list with key value pair

Can someone help me with this super newbie python problem. I tried googling multiple times.

This is the list I have been provided:

fruits = [{"key":"Red","value":"Apple"},
 {"key":"Yellow-0","value":"Mango"},
{"key":"Green","value":"Banana"}]

In some cases it could also be just:

fruits = [{"key":"Yellow-0","value":"Mango"}]

Problem Statement

I want to iterate over this list and match only when there's a Yellow-0 or Yellow-1 and so on until Yellow-9

My code

import re

fruits = [{"key":"Red","value":"Apple"},
 {"key":"Yellow-0","value":"Mango"},
{"key":"Green","value":"Banana"}]

keyword = r"Yellow-\d"

for key in fruits:
    if keyword:
        print(fruits)

My Output:

[{'key': 'Red', 'value': 'Apple'}, {'key': 'Yellow-0', 'value': 'Mango'}, {'key': 'Green', 'value': 'Banana'}]
[{'key': 'Red', 'value': 'Apple'}, {'key': 'Yellow-0', 'value': 'Mango'}, {'key': 'Green', 'value': 'Banana'}]
[{'key': 'Red', 'value': 'Apple'}, {'key': 'Yellow-0', 'value': 'Mango'}, {'key': 'Green', 'value': 'Banana'}]

My Desired Output is to match Yellow-0 and return true as this will be part of a function

Yellow-0

Upvotes: 1

Views: 120

Answers (3)

Islem
Islem

Reputation: 1

You havn't implemented your list the right way, here is a simple solution without the need of importing some library. hope it's helpful

#the name 'key' and 'value' are hundled by the dictionary brakets "{}" for that 
you do not need to write them

fruits = [{ "Apple": "Red"}, {"Mango": "Yellow-0"}, {"Banana": "Green"}]

#this is the string value you search for

DesiredString = "Yellow-0"

#Nested for loop to iterate over two stage [the fruit stage, and the key_value 
stage

for fruit in fruits :
    for key, value in fruit.items() :
        if value == DesiredString :
            print(key)

Upvotes: 0

alvrm
alvrm

Reputation: 363

I haven't used regular expressions in Python, but this will probably work:

pattern = re.compile("Yellow-\d")
for fruit in fruits:
      if pattern.match(fruit['value']):
          print(fruit['value'])

And if it could be in 'key'...

pattern = re.compile("Yellow-\d")
for fruit in fruits:
      match = fruit['value'] if pattern.match(fruit['value']) else False
      match = fruit['key'] if not match and pattern.match(fruit['key']) else False
      if match:
          print(match)

And using the Ternary Operator var = [value_1] if [condition] else [value_2] keeps things organized so you dont have nested if/else statements to clutter the code.

Upvotes: 3

Sterios
Sterios

Reputation: 31

why do you import re without using it?

You have a list of dictionaries:

for fruit in fruits:
      for key, value in fruit.items():
            if value ==  <your string>:
                  print(value) 

Upvotes: 1

Related Questions