Zerhinne
Zerhinne

Reputation: 2057

Finding values in a list of key/value pairs

I have 2 lists

old_name_list = [a-1234, a-1235, a-1236]
new_name_list = [(a-1235, a-5321), (a-1236, a-6321), (a-1234, a-4321), ... ]

I want to search recursively if the elements in old_name_list exist in new_name_list and returns the associated value with it, for eg. the first element in old_name_list returns a-4321, second element returns a-5321, and so on until old_name_list finishes.

I have tried the following and it doesn't work

for old_name, new_name in zip(old_name_list, new_name_list):
    if old_name in new_name[0]:
        print new_name[1]

Is the method I am doing wrong or I have to make some minor changes to it? Thank you in advance.

Upvotes: 2

Views: 7699

Answers (3)

Burhan Khalid
Burhan Khalid

Reputation: 174662

Use this:

found_items = [item[1] for item in new_name_list if item[0] in old_name_list]

Upvotes: 3

Samy Vilar
Samy Vilar

Reputation: 11130

Using a dictionary may be the best way to do this.

old_name_list = ['a-1234', 'a-1235', 'a-1236']
new_name_list = [('a-1235', 'a-5321'), ('a-1236', 'a-6321'), ('a-1234, a-4321')]
mapping = dict(new_name_list)
values = [mapping[item] if item in mapping for item in old_name_list]
print values

Upvotes: 3

steveha
steveha

Reputation: 76725

Build a dict() based on your second list, and lookup in that.

old_name_list = ["a-1234", "a-1235", "a-1236"]
new_name_list = [("a-1235", "a-5321"), ("a-1236", "a-6321"), ("a-1234", "a-4321") ]

d = dict(new_name_list)

for n in old_name_list:
    print d[n]

You do need to put quotes around strings like "a-1234".

Upvotes: 7

Related Questions