CLASS:XII
TOPIC:Dictionary
Students in this assignment :
I explained about the Dictionary ie one of the most important data
type of python .It is MUTABLE data type .In which we can change ,
update, Modify the value etc so its example shows that it is mutable
type data ins python
Below I made the “content in serial order with example” through
which we can :
Create ,modify,test in the dictionary in easy way.
Copy this in your notebook.
On the basis of this explaination you solve the question ie.given in the
homework option
1. Introduction of dictinary
2. Create an empty dictionary
3. Create a dictionary with some pairs
4. Print all keys
5. Accessing
6. Sorting
7. Iterating over (key, value) pairs
8. Combining List and Dictionary
9. Print the uid and name of each customer
10. Modify an entry
11. Add a new field to each entry
12. Delete a field
13. Delete all fields
Dictionary in Python:
A dictionary is a collection which is unordered, changeable and
indexed. In Python dictionaries are written with curly brackets,
and they have keys and values.
Dictionary Manipulation in Python
A dictionary is a collection of key-value pairs.
A dictionary is a set of key:value pairs.
All keys in a dictionary must be unique.
In a dictionary, a key and its value are separated by a colon.
The key, value pairs are separated with commas.
The key & value pairs are listed between curly brackets " { } "
We query the dictionary using square brackets " [ ] "
Dictionary Manipulation
Dictionaries are useful whenever you have to items that you wish to link together,
and for example storing results for quick lookup.
Create an empty dictionary
months = {}
Create a dictionary with some pairs
# Note: Each key must be unique
months = { 1 : "January",
2 : "February",
3 : "March",
4 : "April",
5 : "May",
6 : "June",
7 : "July",
8 : "August",
9 : "September",
10 : "October",
11 : "November",
12 : "December" }
months[1-12] are keys and "January-December" are the values
Print all keys
print "The dictionary contains the following keys: ", months.keys()
Output:
Example:
The dictionary contains the following keys: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Accessing
To get a value out of a dictionary, you must supply its key, you cannot provide
the value and get the key
whichMonth = months[1]
print whichMonth
Output: January
To delete an element from a dictionary, use del
del(months[5])
print months.keys()
Output:
[1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12]
To add a new element to a dictionary, assign a value to a new key
months[5] = "May"
print months.keys()
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
To update an element of a dictionary, assign a new value to its key
months[1] = "Jan"
print months
Output:
{1: 'Jan', 2: 'February', 3: 'March', 4: 'April', 5... }
Sorting
sortedkeys = months.keys()
print sortedkeys
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Dictionaries and Loops
Iterating over keys
for key in months:
print key, months[key]
Output:
1 January
2 February
3 March
4 April
5 May
6 June
7 July
8 August
9 September
10 October
11 November
12 December
Iterating over (key, value) pairs
for key, value in months.iteritems():
print key, value
print "The entries in the dictionary are:"
for item in months.keys():
print "months[ ", item, " ] = ", months[ item ]
Combining List and Dictionary
Example of a list of dictionaries
customers = [{"uid":1,"name":"John"},
{"uid":2,"name":"Smith"},
{"uid":3,"name":"Andersson"},
]
print customers
Output:
[{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3, 'name':
'Andersson'}]
Print the uid and name of each customer
for x in customer:
print x["uid"], x["name"]
Output:
1 John
2 Smith
3 Andersson
Modify an entry
This will change the name of customer 2 from Smith to Charlie
customers[2]["name"]="charlie"
print customers
Output:
[{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3, 'name':
'charlie'}]
Add a new field to each entry
for x in customers:
x["password"]="123456"
# any initial value
print customers
Output:
[{'password': '123456', 'uid': 1, 'name': 'John'}, {'password': '123456', 'uid':
2, 'name': 'Smith'}, {'password': '123456', 'uid': 3, 'name': 'Andersson'}]
Delete a field
del customers[1]
print customers
Output:
[{'uid': 1, 'name': 'John'}, {'uid': 3, 'name': 'Andersson'}]
Delete all fields
# This will delete id field of each entry.
for x in customers:
del x["id"]
Output:
[{'name': 'John'}, {'name': 'Smith'}, {'name': 'Andersson'}]
Create a new dictionary
# In order to construct a dictionary you can start with an empty one.
>>> mydict={}
# This will create a dictionary, which has an initially six key-value
pairs, where iphone* is the key and years the values
released = {
"iphone" : 2007,
"iphone 3G" : 2008,
"iphone 3GS" : 2009,
"iphone 4" : 2010,
"iphone 4S" : 2011,
"iphone 5" : 2012
}
print released
>>Output
{'iphone 3G': 2008, 'iphone 4S': 2011, 'iphone 3GS': 2009, '
iphone': 2007, 'iphone 5': 2012, 'iphone 4': 2010}
*Add a value to the dictionary
You can assign to an individual dictionary entry to add it or modify it
#the syntax is: mydict[key] = "value"
released["iphone 5S"] = 2013
print released
>>Output
{'iphone 5S': 2013, 'iphone 3G': 2008, 'iphone 4S': 2011, 'iphone 3GS':
2009,
'iphone': 2007, 'iphone 5': 2012, 'iphone 4': 2010}
*Remove a key and it's value
You can remove key-value pairs with the del operator
del released["iphone"]
print released
>>output
{'iphone 3G': 2008, 'iphone 4S': 2011, 'iphone 3GS': 2009, 'iphone 5':
2012,
'iphone 4': 2010}
*Check the length
The len() function gives the number of pairs in the dictionary.
print len(released)
*Test the dictionary
Check if a key exists in a given dictionary by using the in operator like
this:
>>> my_dict = {'a' : 'one', 'b' : 'two'}
>>> 'a' in my_dict
True
>>> 'b' in my_dict
True
>>> 'c' in my_dict
False
or like this in a for loop
for item in released:
if "iphone 5" in released:
print "Key found"
break
else:
print "No keys found"
>>output
Key found
*Get a value of a specified key
print released.get("iphone 3G", "none")
*Print all keys with a for loop
print "-" * 10
print "iphone releases so far: "
print "-" * 10
for release in released:
print release
>>output
----------
iphone releases so far:
----------
iphone 3G
iphone 4S
iphone 3GS
iphone
iphone 5
iphone 4
*Print all key and values
for key,val in released.items():
print key, "=>", val
>>output
iphone 3G => 2008
iphone 4S => 2011
iphone 3GS => 2009
iphone => 2007
iphone 5 => 2012
iphone 4 => 2010
*Get only the keys from the dictionary
phones = released.keys()
print phones
# or print them out like this:
print "This dictionary contains these keys: ", " ".join(released)
>>iphone 3G iphone 4S iphone 3GS iphone iphone 5 iphone 4
# or like this:
print "This dictionary contains these keys: ", " ", released.keys()
>>['iphone 3G', 'iphone 4S', 'iphone 3GS', 'iphone', 'iphone 5', 'iphone 4']
Printing the values
Elements may be referenced via square brackets, using the key: print
released["iphone"]
print "Values:
",
for year in released:
releases= released[year]
print releases
>>output:
Values:
2008
2011
2009
2007
2012
2010
Sorting the dictionary
for key, value in sorted(released.items()):
print key, value
>>output:
('iphone', 2007)
('iphone 3G', 2008)
('iphone 3GS', 2009)
('iphone 4', 2010)
('iphone 4S', 2011)
('iphone 5', 2012)
Counting
count = {}
for element in released:
count[element] = count.get(element, 0) + 1
print count
>>output:
{'iphone 3G': 1, 'iphone 4S': 1, 'iphone 3GS': 1, 'iphone': 1,
'iphone 5': 1, 'iphone 4': 1}