python how to match text to other text?

Question:

What I mean is, for example this to be the final output:

example1 = text of example 1
example2 = text of example 2
example3 = text of example 3
list1 = ['example1', 'example3',  'example2']
list2 = ['text of example 1', 'text of example 3', 'text of example 2']
for a in list1:
  if a in list2:
    print(a)

This is my first code, i can’t make it work. Any help?

Asked By: Inj3ct0r

||

Answers:

Use a dictionary to store values. For example:

d = {}
for variable_name, value in zip(list1, list2):
    d[variable_name] = value

Then you can access the value under example1 key like this: print(d['example1'])

P.S. "example1" in "example 1" will evaluate to False

Answered By: Viliam Popovec

Improved the dictionary answer by Viliam Popovec because it had a problem. The dictionary values would then all be equal to "text of example 3"

I sorted both arrays and then simply matched the key with pairs using the same index.

list1 = ['example1', 'example3',  'example2']
list2 = ['text of example 1', 'text of example 3', 'text of example 2']

list1.sort()
list2.sort()

d = {}

for i in range(len(list1)):
        d[list1[i]] = list2[i]

print(d)

I hope this helps.

Answered By: Inshaullah
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.