I want to see the dictionary keys that match the elements in the Python list and their values.

Asked 1 years ago, Updated 1 years ago, 302 views

I'm a beginner at Python, so there might be something strange about it.I would appreciate it if you could point it out.

A(list) = ['Fish', 'Tori', 'Dog', 'Cat', 'Rabbit']
B (dictionary) = {'Fish': 'Tuna', 'Katsuo', 'Dog': 'Shiba-nu', 'Pomeranian'}

(I wrote a simple list and dictionary for explanation, but there are actually more.)

If there is a list and dictionary like the one above, I would like to see the key and the value if the element A exists in the key B.

I would appreciate it if the results were as follows.

 'Fish': 'Tuna', 'Katsuo'
'Dog': 'A little dog', 'Pomeranian'

python

2022-12-15 07:23

1 Answers

B is a value similar to the following (key is a string and value is listed):

A=['Fish', 'Tori', 'Dog', 'Cat', 'Rabbit']
B = {'Fish': ['Tuna', 'Katsuo', 'Dog': ['Shiba'', 'Pomeranian']}

matched = {a:B[a] for a if a in B}
print(matched)

# {'Fish':['Maguro', 'Katsuo', 'Dog':['Shiba Dog', 'Pomeranian']}


2022-12-15 08:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.