Dictionaries
-
Upload
salma-subh -
Category
Technology
-
view
411 -
download
0
Transcript of 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.
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’ }
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 \
2- Dictionary operations
* The del statement removes a key-value pair from a dictionary.
** change any value
*** The len function also works on dictionaries; it returns the number of key-value pairs:
3-Dictionary methods
>> .keys() >> .values() >> .items() >> .has_key()
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 \
Copyin
gIf you want to modify a dictionary and keep a copy of the original,
use thecopy method ,,,
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:
نفس على تؤشر و ال من كلال في العناصر عناوين أو العناصر
copy
userRAM
copy user
ahmed
karim
ali
If we modify copy, opposites is unchanged:
nice program
counting the number of letter in word ..
Good luck !By /salma subh