DICTIONARIES Notes
DICTIONARIES Notes
KEY-VALUE PAIR
What is Dictionary
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. Thats why
python dictionaries are known as KEY:VALUE
pairs.
- A number
mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000}
for key in mydict:
print(key,'=',mydict[key])
Accessing keys and valuessimultaneously
>>> mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000}
>>>mydict.keys()
dict_keys(['empno', 'name', 'dept', 'salary'])
>>>mydict.values()
dict_values([1, 'Shivam', 'sales', 25000])
Wecan convert the sequence returned by keys() and values() by using list()
as shown below:
>>> list(mydict.keys())
['empno', 'name', 'dept', 'salary']
>>> list(mydict.values())
[1, 'Shivam', 'sales', 25000]
Characteristics of a Dictionary
Unordered set
Adictionary is a unordered set of key:value pair
Not a sequence
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
Dictionaries are indexed by keys. Keys are immutable
type
Characteristics of a Dictionary
Keys must be unique
Each key within dictionary must be unique. However two unique
keys can have samevalues.
>>> data={1:100, 2:200,3:300,4:200}
Mutable
Like lists, dictionary are also mutable. We can change the value
of a certain “key” in place
Data[3]=400
>>>Data
So, to change value of dictionary the format is :
DictionaryName[“key” / key]=new_value
You can not only change but you can add new key:value pair :
Dictionaryname[“New Key”]=Value
Internally stored as Mappings
Internally, the key:value pair are associated with
one another with some internal function(called hash
function). Thisway of linking is called mapping
Given value is
assigned to each key
List is assigned to
each key, as the list
updated dictionary
key values are
automatically
updated
Dictionary functions and methods
copy() : as the name suggest, it will create a copy of dictionary.