Python Dictionary

« Previous Tutorial Next Tutorial »

Dictionary are simply the kind of hash table type. Dictionary in python, works like associative arrays or hashes found in Perl and consists of key-value pairs. Dictionaries are enclosed within the curly braces {} and the values can be assigned and accessed using the square braces [].

Python Dictionary Example

Here is an example program, demonstrates the concept and use of dictionary in python:

# Python Dictionary - Example Program

dictionary1 = {}
dictionary1['one'] = "This is one"
dictionary1[2]     = "This is two"

smalldictionary = {'name': 'Devraj','id':9388, 'branch': 'cs'}

print(dictionary1[2])             # this will print the values for 2 key
print(dictionary1['one'])         # this will print the value for 'one' key
print(smalldictionary)            # this will print the complete dictionary
print(smalldictionary.keys())     # this will print all the keys
print(smalldictionary.values())   # this will print all the values 

Here is the sample output of the above python program:

python dictionary

« Previous Tutorial Next Tutorial »


Quick Links
Signup - Login - Give Online Test