Introduction of Dictinary
Introduction of Dictinary
TOPIC:Dictionary
Students in this assignment :
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.
The key & value pairs are listed between curly 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 = {}
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
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]
months[5] = "May"
print months.keys()
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Sorting
sortedkeys = months.keys()
print sortedkeys
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Modify an entry
Delete a field
del customers[1]
print customers
Output:
[{'uid': 1, 'name': 'John'}, {'uid': 3, 'name': 'Andersson'}]
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
phones = released.keys()
print phones
# or like this:
print "This dictionary contains these keys: ", " ", released.keys()
>>['iphone 3G', 'iphone 4S', 'iphone 3GS', 'iphone', 'iphone 5', 'iphone 4']
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}