Q:

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

belongs to collection: Python Dictionary Programs

0

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. 

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)

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

# 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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Dictionary Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to create a dictionary with mixed k... >>
<< Python program to create a dictionary from a seque...