Home > OS >  How to check if the current item's key name matches a certain string in Python?
How to check if the current item's key name matches a certain string in Python?

Time:11-04

I'm looping through two lists "rows" and "columns" to create a dictionary "fields", which should look like that:

fields = {
  "A0": " ", 
  "A1": " ", 
  "A2": " ",
  ...
  "A7": " ",
  "B0": " ",
  "B1": " ",
  ...
  ...
  "H6": " ",
  "H7": " " 
}

After each of the items is created, I want to check whether the current item's key matches a certain variable, e.g. apple="A1". If that's the case, the value of the key "A1" shall be changed to "O". I tried the following, note that "current_field_key" is just a placeholder for the right expression I'm not able to find:

apple = "A1"
rows = ["A", "B", "C", "D", "E", "F", "G", "H"]
columns = ["0", "1", "2", "3", "4", "5", "6", "7"]
fields = {}
for r in rows:
  for c in columns:
    fields[r c] = " "
    if current_field_key == apple:
      fields["A1"] = "O"

I already thought about accessing the item's key name via creating a list of all key names and check for the index, but I don't know how to find the right index without making it too complicated:

if list(fields.keys())[index] == apple:
  fields["A1"] = "O"

Thanks in advance!

CodePudding user response:

you can use this expression to check if key is similar to the apple.

for r in rows:
  for c in columns:
    fields[r c] = " "
    if r c == apple:
      fields[r c] = "O"      

This way you are checking if current key is equal to what you want.

CodePudding user response:

You can do the following to find a key and update its value to "O":

fields = {}
for r in rows:
    for c in columns:
        key = r c
        fields[key] = " "
        if key == apple:
            fields[key] = "O"

Or you can first populate the dictionary and then use the get function to do the check:

fields = {}
for r in rows:
    for c in columns:
        fields[r c] = " "

if fields.get(apple):
    fields[apple] = "O"
  • Related