0 ratings 0% found this document useful (0 votes) 39 views 7 pages Dictionary Notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save dictionary_notes For Later What is Dictionary
2 nee
0 It is another collection in Python but with different in
way of storing and accessing. Other collection like
list, tuple, string are having an index associated
with every element but Python Dictionary have a
“key” associated with every element. That’s why
python dictionaries are known as KEY:VALUE pairs.
© Like with English dictionary we search any word for
meaning associated with it, similarly in Python we
search for “key” to get its associated value rather
than searching for an index.
Creating a Dictionary
2 Eee
Syntax to create dictionary:
dictionary_name = {key 1:value,key2:value,....}
Example
>>> emp = {"empno":
ame":"Shahrukh","fee":1 500000}
Here Keys are : “empno”, “name” and “fee”
Values are: 1, “Shahrukh”, 1500000
Note:
) Dictionary elements must be between curly brackets
2) Each value must be paired with key element
») Each key-value pair must be separated by comma(,)
5 Diet] = G # empty dictionary
© DaysinMonth=("Jan":31,"Feb":28,"Mar":31,"Apr"s3 1
Note: Keys of dictionary must of immutable type such as:
A python string
A number
- Atuple(containing only immutalsle entries)
If we try to give mutable type as key, python will give an error
S>>dict2 = {[2,3]:"abe"} ErrorAccessing elements of Dictionary
a
5 To access Dictionary elements we need the “key”
>>>mydict={'empno':1,'name':'Shivam','dept’:'sales','salary':25000}
>>> mydict['salary']
25000
Note: if you try to access “key” which is not in the dictionary, python
will raise an error
>>>mydiet[‘comm'] #Error
Traversing a Dictionary
Ss
4 Python allows to apply “for” loop to traverse every
element of dictionary based on their “key”. For loop
will get every key of dictionary and we can access
every element based on their key.
Accessing keys and values simultaneously
a
>>> mydict={‘empno':1,‘name’:'Shivam’,‘dept’:'sales’,'salary':25000}
>>>mydictkeys()
dict_keys(['empno’, ‘name’, ‘dept’, 'salary'])
>>>mydietvalues()
dict_values({1, ‘Shivam’, ‘sales’, 25000)
We can convert the sequence returned by keys() and values() by using list()
as shown below:
>>> list(mydict.keys())
[empno’, ‘name’, ‘dept’, 'salary']
[1, ‘Shivam’, ‘sales’, 25000]Characteristics of a Dictionary
ee
5 Unordered set
© A dictionary is a unordered set of key:value pair
© Not a sequence
5 Unlike a string, tuple, and list, a dictionary is not a sequence
because it is unordered set of elements. The sequences are
indexed by a range of ordinal numbers. Hence they are
ordered but a dictionary is an unordered collection
© Indexed by Keys, Not Numbers
5 Dictionaries are indexed by keys. Keys are immutable
type
© Keys must be unique
5 Each key within dictionary must be unique. However two unique
keys can have same values.
5 >>> data={1:100, 2:200,3:300,4:200}
© Mutable
1 Like lists, dictionary are also mutable. We can change the value
of a certain “key” in place
© Data[3]=400
5 >>>Data
5 So, to change value of dictionary the format is :
= DictionaryName|"key” / key ]=1
5 You can not only change but you can add new key:value pair :
© Multiple ways of creating dictionaries
1. Initializing a Dictionary : in this method all the key:value
pairs of dictionary are written collectively separated by
commas and enclosed ~—sin’~—scurly. braces
Student={““roll”:1,"name”:"Scott”,/"Per”:90}
2 Adding key:value pair to an empty Dictionary = in this
method we first create empty dictionary and then
key:value pair are added to it one pair at a time
For example
Alphabets={} #Empty dictionary
Or
Alphabets = dict()co Multiple ways of creating dictionaries
Now we will add new pair to this empty dictionary one by one
as:
Alphabets = {}
Alphabets[“a”]="apple”
Alphabets[“b"]="boy”
3. Creating dictionary from name and value pairs: using the
dict() constructor of dictionary, you can also create dictionary
initialized from specified set of keys and values. There are
multiple ways to provide keys and value to dict()
(i) Specific key:value pairs as keyword argument to dict()
Student=dict(roll=1,name='‘scott’,per=89)
2 Multiple ways of creating dictionaries
(ji) Specify comma-separated key:value pairs
student = dict({‘roll’:1,/name’:’scott’,’ per’:89})
(iii) Specify keys separately and corresponding values
separately: in this method keys and values are enclosed
separately in parenthesis and are given as arguments to
the zip() inside diet()
Emp = dict(zip((‘empno’,’name' 'dept’),(1,'Seott","HR")))
(iv) Specify key:value pairs separately in form of
sequences : in this method one list of tuple argument is
passed to dict(). These list or tuple contains individual
key-value pair
Example:
Emp = dict([‘name’,'Victor’],[‘dept’,’sales'])
Or
Emp = dict(((‘name’,’john’),(‘dept’ it’), (‘sal’, 1 200)))Adding elements to Dictionary
1 You can add new element to dictionary as :
5 dictionaryName[“key"] = value
© Nesting Dictionaries : you can add dictionary as
value inside a dictionary. This type of dictionary
known as nested dictionary. For example:
Visitor =
{‘Name’:'Scott’,/,Address':{*hno’:'11A/B’,'City’:'Kanpur’,
*PinCode’:’208004'},
‘Name’:’Peter’,/Address’:{‘hno’:'11B/A’/'City’:’Kanpur’,’
PinCode’:’208004'
© To print elements of nested dictionary is as :
>>> Visitor =
{'Name''Scott’,Address''hno':'1 1A/B"/City':Kanpur’,'PinCode'
'208004'}}
>>> Visitor
{'Name’: 'Scott’, ‘Address’: {‘hno': '114/B', ‘City’: ‘Kanpur’, 'PinCode’:
"2080
04'}}
>>> Visitor['Name']
"Scott"
>>> Visitor['Address']['City'] _ # to access nested elements
‘Kanpur’
Updating elements in Dictionary
Ll
© Dictionaryname[“key”]=value
>>> data={1:100, 2:200,3:300,4:200}
>>> data[3]=1500
>>> data[3] # 1500Deleting elements from Dictionary
0 Eee
del dictionaryName[“Key”]
>>> D1 = {1:10,2:20,3:30,4:40}
>>> del D1[2]
>>> D1
1:10,2:20,4:40
- If you try to remove the item whose key does not
exists, the python runtime error occurs.
- Del D1[5] #ErrorChecking the existence of key
a
co We can check the existence of key in dictionary
using “in” and “not in”.
>>>alpha={"a":"apple","b"."boy","c":"cat","d"."dog"}
>>> 'a' in alpha
True
>>>’e’ in alpha
False
>>>’e’ not in alpha
True
0 If you pass “value” of dictionary to search using “in”
it will return False
>>>’apple’ in alpha
False
To search for a value we have to search in
dict.values()
>>>’apple’ in alpha.values()