Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views

04 Python Dictionary

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

04 Python Dictionary

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Python Dictionary

• The dictionary is a collection that contains key: value pairs separated by commas inside curly
brackets.

capitals = {"India" : "New Delhi", "France" : "Paris", "Bangladesh" : "Dhaka"}

• Dictionary items are ordered (from version 3.7 onwards), changeable, and does not allow duplicates.
• Keys are immutable but values are mutable.

• Keys must be a single element

• Value can be any type such as list, tuple, integer, etc.


• It is more generally known as an associative array.
• Keys are unique within a dictionary while values may not be.

Adding elements to a Dictionary


In Python Dictionary, the Addition of elements can be done in multiple ways. One value at a time can be added
to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’.
Updating an existing value in a Dictionary can be done by using the built-in update() method. Nested key
values can also be added to an existing Dictionary.

Note- While adding a value, if the key-value already exists, the value gets updated otherwise a new Key with
the value is added to the Dictionary.

Capitals[‘Sri lanka’] = ‘Colombo’

Accessing elements from a Dictionary


In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets.
Print(capitals[‘India’])

Removing Elements from Dictionary


1. Using del keyword
In Python Dictionary, deletion of keys can be done by using the del keyword. Using the del keyword, specific
values from a dictionary as well as the whole dictionary can be deleted. Items in a Nested dictionary can also
be deleted by using the del keyword and providing a specific nested key and particular key to be deleted from
that nested Dictionary.

Note: The del Dict will delete the entire dictionary and hence printing it after deletion will raise an Error.
del capitals[‘France’]

2. Using pop() method


Pop() method is used to return and delete the value of the key specified.

Popped_element = capitals.pop(‘Sri Lanka’)

3. Using popitem() method


The popitem() returns and removes an arbitrary element (key, value) pair from the dictionary.

Popped_element = capitals.popitem()

4. Using clear() method


All the items from a dictionary can be deleted at once by using clear() method.
Capitals.clear()

Len Method
Python dictionary method len() gives the total length of the dictionary. This would be equal to the number of
items in the dictionary.
dict = {'Name': 'Zara', 'Age': 7};
print "Length : %d" % len (dict)

d.get(<key>[, <default>])
Returns the value for a key if it exists in the dictionary.

The Python dictionary .get() method provides a convenient way of getting the value of a key from a dictionary
without checking ahead of time whether the key exists, and without raising an error.

d.get(<key>) searches dictionary d for <key> and returns the associated value if it is found. If <key> is not
found, it returns None:

>>> d = {'a': 10, 'b': 20, 'c': 30}

>>> print(d.get('b'))
20
>>> print(d.get('z'))
None

d.items()
Returns a list of key-value pairs in a dictionary.

d.items() returns a list of tuples containing the key-value pairs in d. The first item in each tuple is the key, and
the second item is the key’s value:

>>> d = {'a': 10, 'b': 20, 'c': 30}


>>> d
{'a': 10, 'b': 20, 'c': 30}

>>> list(d.items())
[('a', 10), ('b', 20), ('c', 30)]
>>> list(d.items())[1][0]
'b'
>>> list(d.items())[1][1]
20

d.keys()
Returns a list of keys in a dictionary.

d.keys() returns a list of all keys in d:

>>> d = {'a': 10, 'b': 20, 'c': 30}


>>> d
{'a': 10, 'b': 20, 'c': 30}

>>> list(d.keys())
['a', 'b', 'c']

d.values()
Returns a list of values in a dictionary.
d.values() returns a list of all values in d:

>>> d = {'a': 10, 'b': 20, 'c': 30}


>>> d
{'a': 10, 'b': 20, 'c': 30}

>>> list(d.values())
[10, 20, 30]

d.update(<obj>)
Merges a dictionary with another dictionary or with an iterable of key-value pairs.

>>> d1 = {'a': 10, 'b': 20, 'c': 30}


>>> d2 = {'b': 200, 'd': 400}

>>> d1.update(d2)
>>> d1
{'a': 10, 'b': 200, 'c': 30, 'd': 400}

>>> d1 = {'a': 10, 'b': 20, 'c': 30}


>>> d1.update([('b', 200), ('d', 400)])
>>> d1
{'a': 10, 'b': 200, 'c': 30, 'd': 400}

>>> d1 = {'a': 10, 'b': 20, 'c': 30}


>>> d1.update(b=200, d=400)
>>> d1
{'a': 10, 'b': 200, 'c': 30, 'd': 400}

Dictionary Methods
Methods Description
copy() They copy() method returns a shallow copy of the dictionary.
clear() The clear() method removes all items from the dictionary.
pop() Removes and returns an element from a dictionary having the given key.
popitem() Removes the arbitrary key-value pair from the dictionary and returns it as
tuple.
get() It is a conventional method to access a value for a key.
dictionary_name.values() returns a list of all the values available in a given dictionary.
str() Produces a printable string representation of a dictionary.
update() Adds dictionary dict2’s key-values pairs to dict
setdefault() Set dict[key]=default if key is not already in dict
keys() Returns list of dictionary dict’s keys
items() Returns a list of dict’s (key, value) tuple pairs
has_key() Returns true if key in dictionary dict, false otherwise
fromkeys() Create a new dictionary with keys from seq and values set to value.
type() Returns the type of the passed variable.
cmp() Compares elements of both dict.

Dictionary vs Lists
Dictionaries and lists share the following characteristics:
• Both are mutable.
• Both are dynamic. They can grow and shrink as needed.
• Both can be nested. A list can contain another list. A dictionary can contain another dictionary. A
dictionary can also contain a list, and vice versa.

Dictionaries differ from lists primarily in how elements are accessed:

• List elements are accessed by their position in the list, via indexing.
• Dictionary elements are accessed via keys.

You might also like