0
my_dict = {'one': 1, 'two': 2, 'three': 3}
my_keys = ['three', 'one','ten','one']

solutions = []
for key,value in my_dict.items():
    found = False
    for i in my_keys:
        if i in key:
           solutions.append(value)
           found = True
           break
        if not found:
           solutions.append('Nan')

I get this output:

['Nan', 1, 'Nan', 'Nan', 'Nan', 'Nan', 3]

but the expected output is:

Output: ['3', '1', 'Nan', '1']

How can I get the expected output?

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Cybertron
  • 155
  • 3
  • 14

2 Answers2

3

Using a list comprehension and dict.get() that can be done like:

Code:

solutions = [my_dict.get(k, 'Nan') for k in my_keys]

Test Code:

my_dict = {'one': 1, 'two': 2, 'three': 3}
my_keys = ['three', 'one', 'ten', 'one']

solutions = [my_dict.get(k, 'Nan') for k in my_keys]
print(solutions)

Results:

[3, 1, 'Nan', 1]
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
1

It seems like you wanted to generate the solutions list with respect to the my_keys list.

Try this:

my_dict = {'one': 1, 'two': 2, 'three': 3}
my_keys = ['three', 'one','ten','one']

solutions = []
for key in my_keys:
    if key in my_dict:
        solutions.append(my_dict[key])
    else:
        solutions.append('Nan')

print(solutions)
Bishakh Ghosh
  • 1,205
  • 9
  • 17