• No results found

The dictionary is indexed ○ The values can be accessed

N/A
N/A
Protected

Academic year: 2022

Share "The dictionary is indexed ○ The values can be accessed"

Copied!
28
0
0

Loading.... (view fulltext now)

Full text

(1)

PROGRAMMING

WITH

PYTHON

Dictionary

(2)

D

ICTIONARY

• Python allows to organize information/data in various ways – Strings, lists and tuples organize data into sequences.

– The strings, lists and tuples are only indexed by integer values.

– These are ordered collection of items.

– The set data-type is an unordered collection of items.

– The elements can’t be accessed in a unique order.

– The set elements cannot be accessed using indexing operators.

(3)

D

ICTIONARY

The dictionary data-type is an unordered collection of items.

Each item consists of key-value pairs

It is ordered collection of references - Each value is referenced though key in the pair

The dictionary is mutable - we can change its state—its length and content.

The dictionary is indexed

The values can be accessed.

The dictionary elements are not only accessed by integer values.

The values can be accessed using float, string, tuple etc.

(4)

D

ICTIONARIES

• Dictionaries stores information in pairs – Similar to an actual dictionary

• Word and definition

• Python uses key and value

Other data types have only value as an element, a dictionary has a pair of entries

A key

A value

The items in dictionaries are accessed using keys and not using their position.

• A dictionary is an associative array (also known as hashes).

• Any key of the dictionary is associated (or mapped) to a value.

(5)

ADVANTAGES

Dictionary is the most powerful data collection of Python.

Dictionaries allow us to do fast database-like operations in python.

The items in dictionaries are accessed using keys and not by the positions.

Dictionaries have different names in different languages

Associative Arrays - Perl / Php

Properties or Map or HashMap - Java

Property Bag - C# / .Net

(6)

D

ICTIONARY

: C

REATION

Place items inside curly braces { } separated by comma.

The dictionary can also be create using dict() function.

An item has a key and the corresponding value expressed as a pair.

key: value

Key and values are separated by a colon

The values can be of any data type and can repeat.

The keys must be of immutable type (integer, float, string, tuple with immutable elements, frozenset etc.)

The keys must be unique.

Example:

age = {'Alice' : 25, 'Bob' :28}

OR

age = dict( {'Alice' : 25, 'Bob' :28} )

(7)

K

EYS MUST BE UNIQUE

>>> age = {'Alice' : 25, 'Bob' : 28, 'Alice' : 26}

>>> age

{'Bob': 28, 'Alice': 26}

(8)

K

EYS MUST BE IMMUTABLE

>>>dict1 = {'BOB':24, 'JOHN':23, 23:23, [1,2]:345}

Traceback (most recent call last):

File "<pyshell#2>", line 1, in <module>

dict1 = {'BOB':24, 'JOHN':23, 23:23, [1,2]:345}

TypeError: unhashable type: 'list'

(9)

D

ICTIONARY

: A

CCESSING

V

ALUES

To access values, dictionary uses keys.

The key is used with

square brackets(Index Operator)

It returns the value corresponding to the key.

If the key is not found, It raises key error.

get() method.

It returns the value corresponding to the key.

If the key is not found, it returns None.

Example:

age = {'Alice' : 25, 'Bob' :28}

age['Alice'] is 25

age.get(‘Bob’) returns 28

(10)

D

ICTIONARY

: D

ISPLAYING

C

ONTENTS

age = {'Alice' : 25, 'Carol': ‘twenty-two’}

items(): It returns all items of the dictionary.

age.items()

dict_items([ ('Alice', 25), ('Carol', 'twenty-two')]) keys(): It returns all keys of the dictionary.

age.keys()

dict_keys([ 'Alice', 'Carol'])

values(): It returns all values of the dictionary.

age.values()

dict_values([28, 25, 'twenty-two'])

(11)

D

ICTIONARIES ARE

M

UTABLE

Dictionary is a mutable data-type, the items can be added/updated.

o The new item can be added using assignment operator or The value of existing items can be updated using assignment operator.

o If the key is already present, value gets updated, else a new key: value pair is added

o The update() can also be used. It updates the value if key exists, otherwise it adds new item. It can be used to add multiple elements in a dictionary.

>>> age = {'Alice' : 25, 'Bob' : 28}

>>> age1 = age

>>> age['Bob'] = 29

>>> age

{'Bob': 29, 'Alice': 25}

>>> age1

{'Bob': 29, 'Alice': 25}

>>> age[‘John'] = 20

>>> age

{'Bob': 29, 'Alice': 25, ‘John’:20}

age.update({‘Kayva’: 29, ‘Haider’:23})

{'Bob': 29, 'Alice': 25, ‘John’:20, ‘Kayva’: 29, ‘Haider’:23}

(12)

D

ICTIONARIES ARE MUTABLE

Dictionaries are mutable, the items can also be removed.

pop() – This method removes a particular item. It takes the key, removes the item and returns the value.

popitem(): The method removes an arbitrary item and returns the item (key, value) form the dictionary. Raises an error, if dictionary is empty.

clear(): This method can be used to clear all items at once.

del: The del keyword can also be used to remove individual items or the entire dictionary itself.

>>> a = {'Alice' : 26, 'Carol' : 22, ‘John’:20, }

>>> a.pop('Carol’) ---- 22 or del a[‘Carol’]

>>> a.popitem() --- ('Alice': 26)

>>> a.clear()

>>>del a

(13)

Dictionary: Method

>>> x = {1:2, 3:4}

>>> type(x)

<class 'dict'>

>>> dir(x)

['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__',

'__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values’]

>>> help(x)

(14)

D

ICTIONARY

: M

ETHODS

A = {1:3, 3:4, 5:6}

len(): Return the length (the number of items) in the dictionary. (len(A))

sorted(): Return a new sorted list of keys in the dictionary. (sorted(A))

copy() --- Return a shallow copy of the dictionary (A.copy()).

fromkeys(seq, v]) ----Return a new dictionary with keys from seq and value equal to v (defaults to None).

{}.fromkeys([1,2,3,4], 23), {}.fromkeys(‘Python’, 2), …..

get(key, d) ----Return the value of key. If key does not exit, return d(defaults to None).

pop(key, d ) ---Remove the item with key and return its value or d if key is not found. If d is not provided and key is not found, raises KeyError.

Setdefault (key, v): Returns the value of the specified key. If the key does not exists; insert the key, with the specified value.

(15)

T

WO

I

TERATION

V

ARIABLES

!

We loop through the key-value pairs in a dictionary using

*two* iteration variables

Each iteration, the first variable is the key and the the second variable is the corresponding value for the key.

Example

dict1 = {'Bob': 29, 'Alice': 25, ‘John’:20, ‘Kayva’: 29,

‘Haider’:23}

for key, value in dict1.items():

print(key, value)

(16)

I TERATION T HROUGH K EYS /V ALUES

Example

dict1 = {'Bob': 29, 'Alice': 25, ‘John’:20, ‘Kayva’: 29,

‘Haider’:23}

for key in dict1.keys():

print(key)

for value in dict1.values():

print(value)

(17)

D

EFINITE

L

OOPS AND

D

ICTIONARIES

Even though dictionaries are not stored in order, 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])

...

...

jan 100 chuck 1 fred 42

>>>

(18)

C

OUNTING

P

ATTERN

The general pattern to count the words in a line of text is to split the line into words, then loop through the words and use a dictionary to track the count of each word independently.

counts = dict()

text = input('Enter a line of text:') words = text.split()

print('Words:', words) print('Counting...') for word in words:

counts[word] = counts.get(word,0) + 1 print('Counts', counts)

(19)

C

OUNTING

W

ORDS

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 {'and': 3, 'on': 1, 'ran': 2, 'car': 3, 'into': 1, 'after': 1, 'clown': 2, 'down': 1, 'fell': 1, 'the': 7, 'tent': 2}

(20)

C

OUNTING

Characters

Frequency of Each Characters

counts = dict()

text = input('Enter a line of text:')

print('Counting...') for letter in text:

counts[letter] = counts.get(letter, 0) + 1 print('Counts', counts)

(21)

Pangram

A pangram, or holo-alphabetic sentence, is a sentence that contains every letter of the alphabet at least once.

The pangram string are as follows

“The quick brown fox jumps over the lazy dog,”

“Sphinx of black quartz, judge my vow”

”Jackdaws love my big sphinx of quartz”

”Pack my box with five dozen liquor jugs”:

”The quick onyx goblin jumps over the lazy dwarf”:

”Cwm fjord bank glyphs vext quiz”:

”How razorback-jumping frogs can level six piqued gymnasts!”

”Cozy lummox gives smart squid who asks for job pen”

(22)

Pangram

counts = dict()

string = input('Enter a line of text:') text = string.casefold()

for letter in text:

counts[letter] = counts.get(letter,0) + 1 List1 = []

for a in counts.keys():

if a.isalpha() == False:

List1.append(a) for a in List1:

counts.pop(a) if len(counts) == 26:

print('The string:', text, 'is pangram') else:

print('The string:', text, 'is not pangram') print('Counts', counts)

(23)

D

ICTIONARY

T

O

L

IST

/S

ET

/T

UPLE

It is possible to create a list of keys/values

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

>>> B = list(A.items())

>>> C = list(A.keys())

>>> D = list(A.values())

>>> B = tuple(A.items())

>>> C = tuple(A.keys())

>>> D = tuple(A.values())

>>> B = set(A.items())

>>> C = set(A.keys())

>>> D = set(A.values())

(24)

L

IST TO

D

ICTIONARY

It is possible to create a dictionary using two lists.

>>> A = ['TajMahal', 'Effiel Tower', 'Statue of Liberty']

>>> B = ['India', ‘France', 'America']

>>> B = zip(A, B)

>>> B

<zip object at 0x104e1d588>

>>> C = list(B)

>>> C

[('TajMahal', 'India'), ('Effil Tower', ‘France'), ('Statue of Liberty', 'America')]

>>> D = dict(C)

>>> D

{'TajMahal': 'India', 'Effil Tower': ‘France', 'Statue of Liberty': 'America'} Or

>>> dict(zip(A, B))

But, What happens when one of the list has one extra elements The extra element will be discarded.

(25)

D

ICTIONARY

>>> dict(zip(list1, list2))

>>> dict(zip(srt1, str2))

>>> dict(zip(tup1, tup2))

>>> dict(zip(set1, set2))

>>> dict(zip(dict1, dict2))

(26)

Programs

• Write a Python script to sort (ascending and descending) a dictionary by value.

• Write a Python script to concatenate three dictionaries to create a new one.

• Write a Python script to merge two Python dictionaries.

• Write a Python script to create a dictionary where the keys are numbers between 1 and 15 (both included) and the values are square of keys.

• Write a Python program to map two lists into a dictionary.

• Write a Python program to remove duplicates values from Dictionary.

• Write a python program to maintain information about each student of Bsc-II.

• Write a Python program to replace dictionary values with their sum.

(27)

Programs

• Write a Python program to combine two dictionary adding values for common keys.

d1 = {'a': 100, 'b': 200, 'c':300}

d2 = {'a': 300, 'b': 200, 'd':400}

Sample output: Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300})

• Write a Python program to create a dictionary from a string.

Sample string : 'w3resource'

Expected output: {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o':

1}

• Write a Python program to create a dictionary from two lists without losing duplicate values.

• Write a Python program to replace dictionary values (integers) with their sum.

(28)

Thank You

References

Related documents

Also the intensity of absorption is directly proportional to the concentration of chemical bonds in a given sample.. Note: The vibration of chemical bonds must involve a change

i is the x-coord of the centroid of the areas given by the blue trapezium, the green trapeziums and the black trapezium.

Since August 2013, book coverage has expanded. Along with the existing book series, book content now includes monographs, edited volumes, major reference works and graduate

Moreover, if it was a case of response bias, e.g., respondents in either the treated or comparison villages over- or under-reported the coping strategies they pursued, why would

• It allows to provide a default value to an argument by using the assignment operator (=) at the time of function definition.. • A default argument assumes a default value if a

For management of COVID-19, Ayurveda will adopt a multi-pronged approach based entirely on classical, time-tested and documented information in Ayurveda (Fig. 3)- (i)

Prediction of rainfall within the six hydrological zones of India was attempted with the oceanic predictors, which highly influence the terrestrial precipitation, such as

The scan line algorithm which is based on the platform of calculating the coordinate of the line in the image and then finding the non background pixels in those lines and