Home > Net >  Python - Iterate the keys and values from the dictionary
Python - Iterate the keys and values from the dictionary

Time:02-03

How can I access the dictionaries key and value and iterate over for loop.

dictioanry= {1: "one", 2: "Two", 3:"Three"}

my output will be like:

1  one
2  two
3  three

CodePudding user response:

You can use this code snippet.

dictionary= {1:"a", 2:"b", 3:"c"}

#To iterate over the keys
for key in dictionary.keys():
    print(key)

#To Iterate over the values
for value in dictionary.values():
    print(value)

#To Iterate both the keys and values
for key, value in dictionary.items():
    print(key,'\t', value)

CodePudding user response:

Use dict.items():

Return a new view of the dictionary’s items ((key, value) pairs)

for key, value in dictioanry.items():
    print(key, value)

Side note: There is a typo in "dictioanry"

CodePudding user response:

Do this to get the desired output:

dictionary= {1: "one", 2: "Two", 3:"Three"}

for i in dictionary.keys():
    print(i, dictionary[i])

Output:

>>> 1 one
2 Two
3 Three
  •  Tags:  
  • Related