0% found this document useful (0 votes)
11 views20 pages

Dictionaries

A collection in Python allows multiple values to be stored in a single variable, with lists and dictionaries being two primary types. Lists are ordered collections accessed by position, while dictionaries are key-value pairs accessed by keys. Python dictionaries maintain insertion order since version 3.7 and provide various methods for manipulation and retrieval of data.

Uploaded by

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

Dictionaries

A collection in Python allows multiple values to be stored in a single variable, with lists and dictionaries being two primary types. Lists are ordered collections accessed by position, while dictionaries are key-value pairs accessed by keys. Python dictionaries maintain insertion order since version 3.7 and provide various methods for manipulation and retrieval of data.

Uploaded by

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

What is a Collection?

• A collection is nice because we can put more than one value in it


and carry them all around in one convenient package

• We have a bunch of values in a single “variable”

• We do this by having more than one place “in” the variable

• We have ways of finding the different places in the variable


What is Not a “Collection”?
Most of our variables have one value in them - when we put a new
value in the variable - the old value is overwritten

$ python
>>> x = 2
>>> x = 4
>>> print(x)
4
A Story of Two Collections..
• List

A linear collection of values >>> A={1:"one",2:"two",3:"three"}


Lookup by position 0 .. length-1
1 one
• Dictionary A= 2 two
3 three
A linear collection of key-value pairs
Lookup by "tag" or "key"
KEYS VALUES
Dictionaries
• Dictionaries are Python’s most powerful data collection

• Dictionaries allow us to do fast database-like operations in Python

• Similar concepts in different programming languages

- Associative Arrays - Perl / PHP

- Properties or Map or HashMap - Java

- Property Bag - C# / .Net


Dictionaries over time in Python
• Prior to Python 3.7 dictionaries did not keep entries in the
order of insertion

• Python 3.7 (2018) and later dictionaries keep entries in


the order they were inserted

• "insertion order" is not "always sorted order"


Lists (Review)
>>> cards = list()
>>> cards.append(12)
• We append values to the >>> cards.append(3)
end of a List and look them >>> cards.append(75)
>>> print(cards)
up by position [12, 3, 75]
>>> print(cards[1])
3
• We insert values into a >>> cards[1] = cards[1] + 2
Dictionary using a key and >>> print(cards)
[12, 5, 75]
retrieve them using a key
Dictionaries
>>> cabinet = dict()
>>> cabinet['summer'] = 12
• We append values to the >>> cabinet['fall'] = 3
end of a List and look them >>> cabinet['spring'] = 75
>>> print(cabinet)
up by position {'summer': 12, fall': 3, spring': 75}
>>> print(cabinet['fall'])
3
• We insert values into a >>> cabinet['fall'] = cabinet['fall'] + 2
Dictionary using a key and >>> print(cabinet)
{'summer': 12, 'fall': 5, 'spring': 75}
retrieve them using a key
Comparing Lists and Dictionaries
Dictionaries are like lists except that they use keys instead of
positions to look up values

>>> lst = list() >>> ddd = dict()


>>> lst.append(21) >>> ddd['age'] = 21
>>> lst.append(183) >>> ddd['course'] = 182
>>> print(lst) >>> print(ddd)
[21, 183] {'age': 21, 'course': 182}
>>> lst[0] = 23 >>> ddd['age'] = 23
>>> print(lst) >>> print(ddd)
[23, 183] {'age': 23, 'course': 182}
Dictionary Literals (Constants)
• Dictionary literals use curly braces and have key : value pairs
• You can make an empty dictionary using empty curly braces

>>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}


>>> print(jjj)
{'chuck': 1, 'fred': 42, 'jan': 100}
>>> ooo = { }
>>> print(ooo)
{}
>>>
Dictionary Tracebacks
• It is an error to reference a key which is not in the dictionary

• We can use the in operator to see if a key is in the dictionary

>>> ccc = dict()


>>> print(ccc['csev'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'csev'
>>> 'csev' in ccc
False
Counting Pattern
counts = dict()
print('Enter a line of text:')
The general pattern to count the
line = input('')
words in a line of text is to split
words = line.split() the line into words, then loop
through the words and use a
print('Words:', words) dictionary to track the count of
print('Counting...')
each word independently.
for word in words:
counts[word] = counts.get(word,0) + 1
print('Counts', counts)
python wordcount.py
Enter a line of text:
the clown ran after the car and the car ran into the tent
and the tent fell down on the clown and the car

Words: ['the', 'clown', 'ran', 'after', 'the', 'car',


'and', 'the', 'car', 'ran', 'into', 'the', 'tent', 'and',
'the', 'tent', 'fell', 'down', 'on', 'the', 'clown',
'and', 'the', 'car']
Counting…

Counts {'the': 7, 'clown': 2, 'ran': 2, 'after': 1, 'car':


3, 'and': 3, 'into': 1, 'tent': 2, 'fell': 1, 'down': 1,
'on': 1}
python wordcount.py
counts = dict() Enter a line of text:
line = input('Enter a line of text:') the clown ran after the car and the car ran
words = line.split()
into the tent and the tent fell down on the
print('Words:', words) clown and the car
print('Counting...’)
Words: ['the', 'clown', 'ran', 'after', 'the', 'car',
for word in words: 'and', 'the', 'car', 'ran', 'into', 'the', 'tent', 'and',
counts[word] = counts.get(word,0) + 1 'the', 'tent', 'fell', 'down', 'on', 'the', 'clown',
print('Counts', counts)
'and', 'the', 'car']
Counting...

Counts {'the': 7, 'clown': 2, 'ran': 2, 'after': 1,


'car': 3, 'and': 3, 'into': 1, 'tent': 2, 'fell': 1,
'down': 1, 'on': 1}
Definite Loops and Dictionaries
We can write a for loop that goes through all the entries in a
dictionary - actually it goes through all of the keys in the dictionary
and looks up the values

>>> counts = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}


>>> for key in counts:
... print(key, counts[key])
...
chuck 1
fred 42
jan 100
>>>
Only Values

OUT PUT
Retrieving Lists of Keys and Values
>>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
You can get a list >>> print(list(jjj))
['chuck', 'fred', 'jan']
of keys, values, or >>> print(list(jjj.keys()))
items (both) from ['chuck', 'fred', 'jan']
a dictionary >>> print(list(jjj.values()))
[1, 42, 100]
>>> print(list(jjj.items()))
[('chuck', 1), ('fred', 42), ('jan', 100)]
>>>

“tuple”
Bonus: Two Iteration Variables!
• We loop through the jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
key-value pairs in a for aaa,bbb in jjj.items() :
print(aaa, bbb)
dictionary using *two*
iteration variables aaa bbb
chuck 1
• Each iteration, the first fred 42 [chuck] 1
jan 100
variable is the key and [fred] 42
the second variable is
the corresponding [jan] 100
value for the key
Pre-Defined Methods
Dictionary Method Meaning
dict.clear() Removes all the elements of
the dictionary
dict.copy() Returns (shallow)copy of
dictionary.
dict.get(key, for key key, returns value or
default=None) default if key not in
dictionary (note that
default's default is None)
dict.items() returns a list of dict's (key,
value) tuple pairs
Contd…
Dictionary Method Meaning
dict.keys() returns list of dictionary
dict's keys
dict.setdefault key, similar to get(), but will set
default=None dict[key]=default if key is not
already in dict
dict.update(dict2) adds dictionary dict2's key-
values pairs to dict
dict.values() returns list of dictionary
dict's values
And few more…

Dictionary Method Meaning


dict.pop() returns list of dictionary
dict's keys
dict.popitem() similar to get(), but will set
dict[key]=default if key is not
already in dict

You might also like