0% found this document useful (0 votes)
6 views10 pages

Dictionary Points

The document provides a comprehensive overview of Python dictionaries, detailing their structure as key-value pairs, characteristics such as mutability, and methods for manipulation including update, copy, clear, pop, items, keys, values, and popitem. It emphasizes the rules regarding keys (which must be unique and immutable) and values (which can be duplicated). Examples illustrate how to create, update, and access dictionary elements, as well as the behavior of various dictionary methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views10 pages

Dictionary Points

The document provides a comprehensive overview of Python dictionaries, detailing their structure as key-value pairs, characteristics such as mutability, and methods for manipulation including update, copy, clear, pop, items, keys, values, and popitem. It emphasizes the rules regarding keys (which must be unique and immutable) and values (which can be duplicated). Examples illustrate how to create, update, and access dictionary elements, as well as the behavior of various dictionary methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 10

---- Dictionary ----

* is {key:value} pair.
* is dynamic and mutable entity.
* is represented within {}.
* every dictionary is object of class "dict".
* does not have natural/automatic indexing (0 onwards).
The keys will behave as index.
* allows over-writing of value by referring "key" as
index.
* does not maintain order of elements. (it is non-linear ds)
* Every "key" must be static and immutable object only;
whereas, "value" can be Python object.
* does not allow duplicate "keys" but duplicate "values"
are allowed.
* does not support slicing-dicing operation.

======================================================

* A dictionary is {k:v} pair.


* Any combination of {k:v} is allowed.

For example:
--------------
d = { "one":1, 2:"two", "three":[3, "III"],
4:("four", "FOUR", "IV"),
}
print(type(d))
print(d)

The output will be:


--------------------
<class 'dict'>
{2: 'two', 4: ('four', 'FOUR', 'IV'), 'three': [3, 'III'], 'one': 1}

===========================================

* If we parse a dictionary in list or tuple or set, then


it will return a sequence of "keys".
For example:
-------------
d = {"one":1, 2:"two", "three":[3, "III"],
4:("four", "FOUR", "IV"),
}
list1 = list(d)
print(list1)

The output will be:


---------------------
['one', 2, 4, 'three']

===========================================

* Logically it is not legal to iterate on dictioary by


using while loop. Because it does not have official
indexing.
* But we can directly iterate on dictionary by using
for-loop. In each iteration of for-loop, it will
refer "keys" of dictionary.
For example:
-------------
one - 1
2 - two
4 - ('four', 'FOUR', 'IV')
three - [3, 'III']

================================================

* It is also valid to obtain and update any value by


referring it's "key".

For example:
-------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345
}
print("Initially d :", d) <--- will print dictionary
print("Mobile number of omkar :", d["omkar"])
# will print mobile number of ["omkar"]
d["tejas"] = 556677
# will update value of ["tejas"]
print("Updated d :", d) <--- will print dictionary

The output will be:


---------------------
Initially d : {'gaurav': 405060, 'tejas': 708090, 'tushar': 12345, 'omkar': 102030}
Mobile number of omkar : 102030
Updated d : {'gaurav': 405060, 'tejas': 556677, 'tushar': 12345, 'omkar': 102030}

========================================

* If any duplicate "key" is provided, then the last


placed {k:v} pair will be considered.

For example:
-------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345,
"gaurav":998877
} <--- key ["gaurav"] is already present
print("Initially d :", d)
print("Mobile number of omkar :", d["omkar"])
d["tejas"] = 556677
print("Updated d :", d)

The output will be:


---------------------
Initially d : {'omkar': 102030, 'tejas': 708090, 'gaurav': 998877, 'tushar': 12345}
Mobile number of omkar : 102030
Updated d : {'omkar': 102030, 'tejas': 556677, 'gaurav': 998877, 'tushar': 12345}

==========================================

* A dicationary is dynamic and mutable object. Therefore


it will update in itself.

For example:
--------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345,
}
print("Initially d :", d)
print(id(d))
d["tejas"] = 556677 <--- updating value of ["tejas"]
print("Updated d :", d)
print(id(d))

The output will be:


--------------------
Initially d : {'gaurav': 405060, 'tushar': 12345, 'omkar': 102030, 'tejas': 708090}
5356680
Updated d : {'gaurav': 405060, 'tushar': 12345, 'omkar': 102030, 'tejas': 556677}
5356680

=======================================================

* To add/change/update anything in dictionary, we have


two options:
1. By using assignment operator (=)
2. By using update()

1. By using assignment operator (=):


* We can directly use "key" as index to update/over-write
"value".
* In such case:
- if specified "key" is already present, then
updates/over-writes it's value
- if specified "key" is not present, then adds them as
new {k:v} pair.
For example:
--------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345,
}
print("Initially d :", d)
d["tejas"] = 445566 <--- key "tejas" is already present
d["amey"] = 778899 <--- key "amey" is not present
print("Updated d :", d)

The output will be:


--------------------
Initially d : {'omkar': 102030, 'tejas': 708090, 'tushar': 12345, 'gaurav': 405060}
Updated d : {'omkar': 102030, 'tejas': 445566, 'amey': 778899, 'tushar': 12345,
'gaurav': 405060}

* From above output, check that value of key "tejas" is


changed/over-write; whereas {"amey":778899} is added
as new {k:v} pair.

2. By using update():
* This is member function of class "dict".
* This function requires another dictionary object as
parameter.
* In such case:
- if specified "key" is already present, then
updates/over-writes it's value
- if specified "key" is not present, then adds them as
new {k:v} pair.

For example:
--------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345,
}
print("Initially d :", d)
d.update({"tejas":445566}) <--- key "tejas" is already present
d.update({"amey":778899}) <--- key "amey" is not present
print("Updated d :", d)

The output will be:


---------------------
Initially d : {'tejas': 708090, 'gaurav': 405060, 'tushar': 12345, 'omkar': 102030}
Updated d : {'tejas': 445566, 'gaurav': 405060, 'tushar': 12345, 'omkar': 102030,
'amey': 778899}

===================================================
===================================================

1. update():
* This function requires another dictionary object as
parameter.
* In such case:
- if specified "key" is already present, then
updates/over-writes it's value
- if specified "key" is not present, then adds them as
new {k:v} pair.

For example:
--------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345,
}
print("Initially d :", d)
d.update({"tejas":445566}) <--- key "tejas" is already present
d.update({"amey":778899}) <--- key "amey" is not present
print("Updated d :", d)

The output will be:


---------------------
Initially d : {'tejas': 708090, 'gaurav': 405060, 'tushar': 12345, 'omkar': 102030}
Updated d : {'tejas': 445566, 'gaurav': 405060, 'tushar': 12345, 'omkar': 102030,
'amey': 778899}

* This method requires a dictionary as parameter. This


parameter dictionary can have any number of {k:v} pairs.

For example:
-------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345,
}
print("Initially d :", d)
d.update( {"tejas":445566, "amey":778899} ) <--- multiple {k:v} pairs
print("Updated d :", d)
The output will be:
---------------------
Initially d : {'tushar': 12345, 'tejas': 708090, 'gaurav': 405060, 'omkar': 102030}
Updated d : {'amey': 778899, 'tejas': 445566, 'tushar': 12345, 'omkar': 102030,
'gaurav': 405060}

=========================================

2. copy():
* This function does not have any parameter.
* This function creates and returns a new copy of invoking
dictionary object.
For example:
-------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345,
}
print("Initially d :", d)
print("ID of original dictionary :", id(d))
d2 = d.copy() <--- creates and returns a new copy
print("Copied d2 :", d2)
print("ID of copied dictionary :", id(d2))

The output will be:


--------------------
Initially d : {'tejas': 708090, 'tushar': 12345, 'gaurav': 405060, 'omkar': 102030}
ID of original dictionary : 40896008
Copied d2 : {'tejas': 708090, 'tushar': 12345, 'gaurav': 405060, 'omkar': 102030}
ID of copied dictionary : 40896456

==============================================

3. clear():
* This function does not have any parameter.
* This function clears all {k:v} pairs from invoking
dictionary object.
For example:
--------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345,
}
print("Initially d :", d)
d.clear()
print("Updated d :", d)

The output will be:


--------------------
Initially d : {'tushar': 12345, 'gaurav': 405060, 'tejas': 708090, 'omkar': 102030}
Updated d : {}

=============================================

4. pop():
* This function requires a "key" as parameter.
* This function removes specified {k:v} pair from invoking
dictionary object.
For example:
--------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345,
}
print("Initially d :", d)
d.pop("tejas") <--- removes {k:v} pair of "tejas"
print("Updated d :", d)

The output will be:


---------------------
Initially d : {'tushar': 12345, 'tejas': 708090, 'gaurav': 405060, 'omkar': 102030}
Updated d : {'tushar': 12345, 'gaurav': 405060, 'omkar': 102030}

* If specified "key" is not present, then this function will


show "KeyError".
For example:
-------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345,
}
print("Initially d :", d)
d.pop("tejasaa") <--- key "tejasaa" is not present
print("Updated d :", d)

The error will be:


-------------------
KeyError: 'tejasaa'

* This function also returns the "value" of specified "key"


which is removed from dictionary.
For example:
-------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345,
}
print("Initially d :", d)
a = d.pop("tejas") <--- removes {k:v} pair but returns value in 'a'
print("Updated d :", d)
print(a)

The output will be:


--------------------
Initially d : {'tejas': 708090, 'omkar': 102030, 'tushar': 12345, 'gaurav': 405060}
Updated d : {'omkar': 102030, 'tushar': 12345, 'gaurav': 405060}
708090

* This function strictly requires exact one "key" as


parameter.
====================================

5. items():
* This function does not have any parameter.
* This function returns an object of new class "dict_items"
where each {k:v} pair will be as tuple elements.
For example:
--------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345,
}
print("Initially d :", d)
a = d.items()
print(a)
print("Type of a :", type(a))

The output will be:


--------------------
Initially d : {'tushar': 12345, 'tejas': 708090, 'gaurav': 405060, 'omkar': 102030}
dict_items([('tushar', 12345), ('tejas', 708090), ('gaurav', 405060), ('omkar',
102030)])
Type of a : <class 'dict_items'>

* The outer main object is of type "dict_items".


* This object contains tuples as it's elemnets.
* And the elements of this tuples will be {k:v} pairs.

================================================

6. keys():
* This function does not have any parameter.
* This function returns all the "keys" of invoking
dictionary object.
* This function will return all the keys as element of
new class "dict_keys".
For example:
--------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345,
}
print("Initially d :", d)
a = d.keys()
print(a)
print("Type of a :", type(a))

The output will be:


--------------------
Initially d : {'omkar': 102030, 'tejas': 708090, 'gaurav': 405060, 'tushar': 12345}
dict_keys(['omkar', 'tejas', 'gaurav', 'tushar'])
Type of a : <class 'dict_keys'>

====================================================
7. values():
* This function does not have any parameter.
* This function returns all the "values" of invoking
dictionary object.
* This function returns all the "values" as object of
new class "dict_values".
For example:
--------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345,
}
print("Initially d :", d)
a = d.values()
print(a)
print("Type of a :", type(a))

The output will be:


---------------------
Initially d : {'omkar': 102030, 'gaurav': 405060, 'tushar': 12345, 'tejas': 708090}
dict_values([102030, 405060, 12345, 708090])
Type of a : <class 'dict_values'>

==================================================

8. popitem():
* This function does not have any parameter.
* This function randomly removes a {k:v} pair from
invoking dictionary object.
For example:
--------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345,
}
print("Initially d :", d)
d.popitem() <--- randomly removes a {k:v} pair
print("Updated d :", d)

The output will be:


---------------------
Initially d : {'gaurav': 405060, 'omkar': 102030, 'tejas': 708090, 'tushar': 12345}
Updated d : {'omkar': 102030, 'tejas': 708090, 'tushar': 12345}

* This function also returns that randomly removed {k:v}


pair as tuple.
For example:
-------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345,
}
print("Initially d :", d)
a = d.popitem()
print("Updated d :", d)
print("Removed :", a)
print("Type of removed pair is :", type(a))

The output will be:


---------------------
Initially d : {'tejas': 708090, 'omkar': 102030, 'gaurav': 405060, 'tushar': 12345}
Updated d : {'omkar': 102030, 'gaurav': 405060, 'tushar': 12345}
Removed : ('tejas', 708090)
Type of removed pair is : <class 'tuple'>

=====================================================

9. get():
* This function requires a "key" as parameter.
* This function obtains and returns value of specified
key.
For example:
-------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345,
}
print("Initially d :", d)
a = d.get("tejas") <--- obtains value of ["tejas"]
print("Value is :", a)

The output will be:


--------------------
Initially d : {'tejas': 708090, 'gaurav': 405060, 'omkar': 102030, 'tushar': 12345}
Value is : 708090

* If any invalid "key" is provided, then this function will


not show any error. But returns None.
For example:
-------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345,
}
print("Initially d :", d)
a = d.get("ashwin") <--- key ["ashwin"] is not present
print("Value is :", a)

The output will be:


---------------------
Initially d : {'gaurav': 405060, 'tejas': 708090, 'tushar': 12345, 'omkar': 102030}
Value is : None

=============================================

10. setdefault():
* This function requires two individual values as parameter.
* Where first parameter will be "key" and second parameter
will be it's "value".
* If specified "key" (first parameter) is already present,
then this function will not update it's new value.
* But if specified "key" (first parameter) is not
present in invoking dictionary object, then only adds as
new {k:v} pair.
For example:
-------------
d = {"omkar":102030, "gaurav":405060,
"tejas":708090, "tushar":12345,
}
print("Initially d :", d)
d.setdefault("tejas", 778899)
# key "tejas" is already present. Hence, will not update it's new value
d.setdefault("amey", 100200)
# key "amey" is not present. Hence, adds as new {k:v} pair
print("Updated d :", d)

The output will be:


---------------------
Initially d : {'gaurav': 405060, 'tejas': 708090, 'omkar': 102030, 'tushar': 12345}
Updated d : {'gaurav': 405060, 'tejas': 708090, 'omkar': 102030, 'tushar': 12345,
'amey': 100200}

* This function requires exact 2 parameters.

=====================================================

11. fromkeys():
* This function is static member function of class "dict".
* Therefore we call it by using class-name only.
(not by invoking object).
* This function has two parameters:
first is ----> a sequence
second is (optional) ----> default values for all keys
* This function creates a dictionary which takes all
the elements of specified sequence (first parameter) as
"keys" and assigns all of them the specified default
value as their "value".
* The second parameter is optional parameter. Becuase it
is having default "None" as initialized value.
For example:
--------------
list1 = ["one", "two", "three", "four"]
d = dict.fromkeys(list1)
print(d)

The output will be:


---------------------
{'three': None, 'two': None, 'four': None, 'one': None}

* From above output note that, all the elements of list1


becomes "keys" and all initialized with default None.
* If we specify default value, then it will be value of
all "keys".
For example:
-------------
list1 = ["one", "two", "three", "four"]
d = dict.fromkeys(list1, "HELLO ALL")
print(d)

The output will be:


--------------------
{'four': 'HELLO ALL', 'two': 'HELLO ALL', 'one': 'HELLO ALL', 'three': 'HELLO ALL'}

* And even if we specify another sequence as second parameter,


then also that entire sequence will be default value
for all "keys"
For example:
--------------
list1 = ["one", "two", "three", "four"]
list2 = [10,20,30,40]
d = dict.fromkeys(list1, list2)
print(d)

The output will be:


---------------------
{'four': [10, 20, 30, 40], 'two': [10, 20, 30, 40], 'one': [10, 20, 30, 40],
'three': [10, 20, 30, 40]}

=====================================================

You might also like