Home > Mobile >  Python Dictionaries where the keys are from a list
Python Dictionaries where the keys are from a list

Time:04-19

How can I print the certain values of a dictionary,where I should iterate it’s keys from a list?

F.e. -> I have a list with codons: [‘AUU’,’GGG’], and let’s assume that auu and ggg is defined in a dictionary as keys, and their values are x and y, I want to be able to read the list throughoutly, and print x and y.

Thanks for the help..

CodePudding user response:

Try this :

keys = ['auu', 'ggg']
a_dict = {'auu': 'x', 'ggg': 'y', 'hhh': 'z'}

for i in keys:
    print(a_dict[i])

CodePudding user response:

Using items() method -> https://www.geeksforgeeks.org/python-dictionary-items-method/

a_dict = {'auu': 'x', 'ggg': 'y', 'hhh': 'z'}

for a, b  in a_dict.items():
    print(a, b)

CodePudding user response:

This code does the job,

test = {"AUU": "x", "GGG": "y"}  

for key in test:
  print(test[key])

OR

test = {"AUU": "x", "GGG": "y"}  

for value in test.values():
  print(value)

Both the code return the same output.

Output -

x
y

If you want to store the values in a list just use,

list(test.values())

test.value() returns you an object of type dict_values which isn't iterable. So passing it inside list() converts it into list, making it iterable.

  • Related