0% found this document useful (0 votes)
3 views

Dictionary declaration

Uploaded by

sunaina bokolia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Dictionary declaration

Uploaded by

sunaina bokolia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Dictionary

• Python's dictionaries are kind of hash table type.


They work like associative arrays and consist of key-
value pairs.
• Dictionaries are enclosed by curly braces ({ }) and
values can be assigned and accessed using square
braces ([])
Commonly used dict methods:
• 1. Each key of Dictionary is mapped to a value.
• 2. Each key is seperated from its value by a colon(:)
• 3. Entire dictionary is enclosed in curly braces.
• 4. Keys are unique while value s may not.
• 5.The values of dictionary can be of any type(Mutable
or immutable) but the keys must be of immutable
type(String, numbers, Tuple)
• 6. Dictionary is mutable. We can add new items or
change the value in existing item.

Commonly used dict methods:
1. <Dictionary Name>={‘key’:’Value’,’Key’:’Value’……}

• 2.Empty Dictionary
• D={ }
• 3. The function dict() is used to create a dictionary with no items
• D=dict()

• keys() - returns an iterable of all keys in the dictionary in the form of list.
• values() - returns an iterable of all values in the dictionary in the form of list.
• items() - returns an iterable list of (key, value) tuples i.e in the form of list of
tuples..
Example of Dictionary
dict = {'name': ‘Ram','code':1234, 'dept': ‘KVS'}
print(dict) # Prints complete dictionary
print(dict.keys()) # Prints all the keys
print(dict.values()) # Prints all the values
print(dict.items())
Output:
{'dept': 'KVS', 'code': 1234, 'name': 'Ram'}
['dept', 'code', 'name']
['KVS', 1234, 'Ram']
[('dept', 'KVS'), ('code', 1234), ('name', 'Ram')]
there is a second way to declare a dict:

sound = dict(dog='bark', cat='meow', snake='hiss')


print(sound.keys()) # Prints all the keys
print(sound.values()) # Prints all the values
Output:
['cat', 'dog', 'snake']
['meow', 'bark', 'hiss']

You might also like