Python program to create a dictionary with integer keys, and print the keys, values & key-value pairs

Here, we are going to learn how to create a dictionary with integer keys, and print the keys, values & key-value pairs in Python?
Submitted by Shivang Yadav, on March 23, 2021

Dictionary

A dictionary contains the pair of the keys & values (represents key : value), a dictionary is created by providing the elements within the curly braces ({}), separated by the commas. 

Dictionary with integer keys

Here, we are creating a dictionary with integer keys and printing the dictionary, it's keys, it's values and key-value pairs.

  • Printing the dictionary – To print a dictionary, just pass the dictionary_name in the print function.
    Syntax:
    print(dictionary_name)
    
  • Printing the keys – To print the dictionary keys only, loop through the dictionary and print it, when we loop through a dictionary it returns the keys.
    Syntax:
    for key in dictionary_name:
        print(key)
    
  • Printing the values – To print the dictionary values only, loop through the dictionary and use the values() method, it returns the dictionary values.
    Syntax:
    for value in dictionary_name.values():
        print(value)
    
  • Print the key-value pairs – To print the keys & values both, loop through the dictionary and use the items() method, it returns the key-value pair.
    Syntax:
    for key,value in dictionary_name.items():
        print(key, value)
    

Python program to create a dictionary with integer keys, and print the keys, values & key-value pairs

# Python program to create a dictionary 
# with integer keys

# creating the dictionary
dict_a = {1 : "India", 2 : "USA", 3 : "UK", 4 : "Canada"}

# printing the dictionary
print("Dictionary \'dict_a\' is...")
print(dict_a)

# printing the keys only
print("Dictionary \'dict_a\' keys...")
for x in dict_a:
    print(x)

# printing the values only
print("Dictionary \'dict_a\' values...")
for x in dict_a.values():
    print(x)

# printing the keys & values
print("Dictionary \'dict_a\' keys & values...")
for x, y in dict_a.items():
    print(x, ':', y)

Output

Dictionary 'dict_a' is...
{1: 'India', 2: 'USA', 3: 'UK', 4: 'Canada'}
Dictionary 'dict_a' keys...
1
2
3
4
Dictionary 'dict_a' values...
India
USA
UK
Canada
Dictionary 'dict_a' keys & values...
1 : India
2 : USA
3 : UK
4 : Canada

Python Dictionary Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.