What is Python Dictionary data type

What is Python Dictionary data type

Python dictionary data type gives us a way to store key and value pair. The key and value pair is separated by colon and the key-value item is separated by comma.

The key of a dictionary can be any immutable data types, such as numbers, real numbers, strings and tuples.

The syntax of creating dictionary.


phonebook = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'} 

The code above creates a dictionary. It has three key-value pairs.

We can also use dictionary to create one to many map.


letterDict = {'vowel':['a','e','i','o','u'],'consonant':['b','c','d','f']}

To loop over the keys of a dictionary, you can use a plain for statement.


d = {'x': 1, 'y': 2, 'z': 3} 
# from w  w  w. ja va 2  s  . c  o  m

for key in d: 
    print key, 'corresponds to', d[key]

The code above generates the following result.

You can use the dict function to construct dictionaries from other mappings or from sequences of (key, value) pairs:


items = [('name', 'Gumby'), ('age', 42)] 
d = dict(items) 
print d 
print d['name'] 

The code above generates the following result.

It can also be used with keyword arguments, as follows:


d = dict(name='Gumby', age=42) 
print d 

The code above generates the following result.

An empty dictionary can be created by {}.


x = {} 
x[42] = 'Foobar' 
print x 

The code above generates the following result.

Dictionary assignment


dict1 = {'A': 'earth', 'B': 80}
dict1['A'] = 'venus' 
dict1['B'] = 6969    
dict1['C'] = 'sunos5' 
# from   w  w w .  j  ava2  s.c  om
print dict1

The code above generates the following result.

Dictionary Keys Are Case-Sensitive


d = {} # from   ww w. java2s . c o  m
d["key"] = "value" 
d["key"] = "other value"
print d 
d["Key"] = "third value"
print d 

The code above generates the following result.





















Home »
  Python »
    Data Types »




Data Types
String
String Format
Tuple
List
Set
Dictionary