Home > Software engineering >  Comparing the strings in key and value of the same dictionary
Comparing the strings in key and value of the same dictionary

Time:10-14

I am looking to solve a problem to compare the string of the key and value of the same dictionary.

To return a dictionary of all key and values where the value contains the key name as a substring.

a = {"ant":"antler", "bi":"bicycle", "cat":"animal"}

the code needs to return the result:

b = {"ant":"antler", "bi":"bi cycle"}

CodePudding user response:

You can iterate through the dictionary and unpack the key and the value at the same time this way:

b = {}
for key, value in a.items():
    if value in key:
        b[value] = key

This will generate your wanted solution. It does that by unpacking both the key and the value and checking if they match afterward. You can also shorten that code by using a dictionary comprehension:

b = {key:value for key, value in a.items() if key in value}

This short line does the exact same thing as the code before. It even uses the same functionalities with only one addition - a dictionary comprehension. That allows you to put all that code in one simple line and declare the dictionary on the go.

CodePudding user response:

answer = {k:v for k,v in a.items() if k in v}

Notes:

  • to iterate over key: value pair we use dict.items();
  • to check if a string is inside some other string we use in operator;
  • to filter items we use if-clause in the dictionary comprehension.

See also:

  • Related