Dictionaries

16
Dictionaries Dictionaries \ Are similar to other compound types except that they can use any immutable type as an index. As an example, we will create a dictionary to translate English words into Spanish. For this dictionary, the indices are strings.

Transcript of Dictionaries

Page 1: Dictionaries

Dictionaries

Dictionaries \ Are similar to other compound types except that they can use any immutable type as an index. As

an example, we will create a dictionary to translate English words into Spanish. For this dictionary, the

indices are strings.

Page 2: Dictionaries

1- create a dictionary

One way to create a dictionary is to start with the empty dictionary and addelements. The empty dictionary is denoted {}:

>> var={}>> var [‘ key1 ’] = ‘value’>> var [‘key 2’] = ‘value 2’

The first assignment creates a dictionary named var ; the other assignmentsadd new elements to the dictionary. We can print the current value of thedictionary in the usual way:

>> print var>> {‘var2’: ‘value 2’ , ‘var1’ : ‘value1’ }

Page 3: Dictionaries
Page 4: Dictionaries

The key-value pairs are not in order! Fortunately, there is no reason to careabout the order, since the elements of a dictionary are never indexed with integerindices. Instead, we use the keys to look up the corresponding values

Hint \

Page 5: Dictionaries

2- Dictionary operations

* The del statement removes a key-value pair from a dictionary.

Page 6: Dictionaries

** change any value

*** The len function also works on dictionaries; it returns the number of key-value pairs:

Page 7: Dictionaries

3-Dictionary methods

>> .keys() >> .values() >> .items() >> .has_key()

Page 8: Dictionaries
Page 9: Dictionaries

If you try to call a method without specifying an object, you get an error. Inthis case, the error message is not very helpful:>>> has_key('one')Name Error: has_key

Hint \

Page 10: Dictionaries

Copyin

gIf you want to modify a dictionary and keep a copy of the original,

use thecopy method ,,,

Page 11: Dictionaries

Copying >>

user and copy refer to the same object; copy refers to a fresh copy of the same dictionary. If we modify user, copy is also changed:

Page 12: Dictionaries

نفس على تؤشر و ال من كلال في العناصر عناوين أو العناصر

copy

userRAM

copy user

ahmed

karim

ali

Page 13: Dictionaries

If we modify copy, opposites is unchanged:

Page 14: Dictionaries

nice program

Page 15: Dictionaries

counting the number of letter in word ..

Page 16: Dictionaries

Good luck !By /salma subh