Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
77 views

Dictionary in Python

The document discusses Python dictionaries, including their syntax, properties, and common methods. Some key points: - Dictionaries are collections of key-value pairs that are unordered, mutable, and indexed. - Keys must be immutable types like strings or numbers, while values can be any type. - Common dictionary methods include copy(), update(), items(), len(), and clear(). - Values can be accessed, added, updated, and removed via their keys. - Dictionaries can be iterated over to access keys and values.

Uploaded by

Violet Shaikh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views

Dictionary in Python

The document discusses Python dictionaries, including their syntax, properties, and common methods. Some key points: - Dictionaries are collections of key-value pairs that are unordered, mutable, and indexed. - Keys must be immutable types like strings or numbers, while values can be any type. - Common dictionary methods include copy(), update(), items(), len(), and clear(). - Values can be accessed, added, updated, and removed via their keys. - Dictionaries can be iterated over to access keys and values.

Uploaded by

Violet Shaikh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Python Programming Dictionary CMP Infotech

Python Dictionary Methods: Copy, Update, Items, Len, Cmp, Str,


Sort
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.

Dictionaries are another example of a data structure. A dictionary is used to map or


associate things you want to store the keys you need to get them. A dictionary in
Python is just like a dictionary in the real world. Python Dictionary are defined into
two elements Keys and Values.

 Keys will be a single element


 Values can be a list or list within a list, numbers, etc.

Syntax for Python Dictionary:


Dict = { ' Tim': 18, xyz,.. }

Dictionary is listed in curly brackets, inside these curly brackets, keys and values
are declared. Each key is separated from its value by a colon (:) while each element
is separated by commas.

Properties of Dictionary Keys

There are two important points while using dictionary keys

 More than one entry per key is not allowed ( no duplicate key is allowed)
 The values in the dictionary can be of any type while the keys must be immutable like
numbers, tuples or strings.
 Dictionary keys are case sensitive- Same key name but with the different case are
treated as different keys in Python dictionaries.

Example
Create and print a dictionary:

CMPINFOTECH pg. 1
Python Programming Dictionary CMP Infotech

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Accessing Items
You can access the items of a dictionary by referring to its key name, inside
square brackets:

Example
Get the value of the "model" key:

x = thisdict["model"]
print(x)

There is also a method called get() that will give you the same result:

Example
Get the value of the "model" key:

x = thisdict.get("model")

Change Values
You can change the value of a specific item by referring to its key name:

Example
Change the "year" to 2018:

thisdict["year"] = 2018

CMPINFOTECH pg. 2
Python Programming Dictionary CMP Infotech

Loop Through a Dictionary


You can loop through a dictionary by using a for loop.

When looping through a dictionary, the return value are the keys of the
dictionary, but there are methods to return the values as well.

Example
Print all key names in the dictionary, one by one:

for x in thisdict:
print(x)

Example
Print all values in the dictionary, one by one:

for x in thisdict:
print(thisdict[x])

Example
You can also use the values() function to return values of a dictionary:

for x in thisdict.values():
print(x)

Example
Loop through both keys and values, by using the items() function:

for x, y in thisdict.items():
print(x, y)

Check if Key Exists


To determine if a specified key is present in a dictionary use the in keyword:

CMPINFOTECH pg. 3
Python Programming Dictionary CMP Infotech

Example
Check if "model" is present in the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")

Dictionary Length
To determine how many items (key-value pairs) a dictionary has, use
the len() method.

Example
Print the number of items in the dictionary:

print(len(thisdict))

Adding Items
Adding an item to the dictionary is done by using a new index key and assigning
a value to it:

Example

thisdict["color"] = "red"
print(thisdict)

Removing Items
There are several methods to remove items from a dictionary:

CMPINFOTECH pg. 4
Python Programming Dictionary CMP Infotech

Example
The pop() method removes the item with the specified key name:

thisdict.pop("model")
print(thisdict)

Example
The popitem() method removes the last inserted item (in versions before 3.7, a
random item is removed instead):

thisdict.popitem()
print(thisdict)

Example
The del keyword removes the item with the specified key name:

del thisdict["model"]
print(thisdict)

Example
The del keyword can also delete the dictionary completely:

del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer
exists.

Example
The clear() keyword empties the dictionary:

thisdict.clear()
print(thisdict)

CMPINFOTECH pg. 5
Python Programming Dictionary CMP Infotech

a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1,
because: dict2 will only be a reference to dict1, and changes made
in dict1 will automatically also be made in dict2.

There are ways to make a copy, one way is to use the built-in Dictionary
method copy().

Example
Make a copy of a dictionary with the copy() method:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)

Another way to make a copy is to use the built-in method dict().

Example
Make a copy of a dictionary with the dict() method:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)

The dict() Constructor


It is also possible to use the dict() constructor to make a new dictionary:

CMPINFOTECH pg. 6
Python Programming Dictionary CMP Infotech

Example
thisdict = dict(brand="Ford", model="Mustang", year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)

Accessing the dictionary values


We have discussed how the data can be accessed in the list and tuple by using the indexing.

However, the values can be accessed in the dictionary by using the keys as keys are unique
in the dictionary.

The dictionary values can be accessed in the following way.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print("Name : %s" %Employee["Name"])
5. print("Age : %d" %Employee["Age"])
6. print("Salary : %d" %Employee["salary"])
7. print("Company : %s" %Employee["Company"])

Output:

<class 'dict'>
printing Employee data ....
Name : John
Age : 29
Salary : 25000
Company : GOOGLE

Python provides us with an alternative to use the get() method to access the dictionary
values. It would give the same result as given by the indexing.

Updating dictionary values


The dictionary is a mutable data type, and its values can be updated by using the specific
keys.

Let's see an example to update the dictionary values.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. print(type(Employee))

CMPINFOTECH pg. 7
Python Programming Dictionary CMP Infotech

3. print("printing Employee data .... ")


4. print(Employee)
5. print("Enter the details of the new employee....");
6. Employee["Name"] = input("Name: ");
7. Employee["Age"] = int(input("Age: "));
8. Employee["salary"] = int(input("Salary: "));
9. Employee["Company"] = input("Company:");
10. print("printing the new data");
11. print(Employee)

Output:

<class 'dict'>
printing Employee data ....
{'Name': 'John', 'salary': 25000, 'Company': 'GOOGLE', 'Age': 29}
Enter the details of the new employee....
Name: David
Age: 19
Salary: 8900
Company:JTP
printing the new data
{'Name': 'David', 'salary': 8900, 'Company': 'JTP', 'Age': 19}

Deleting elements using del keyword


The items of the dictionary can be deleted by using the del keyword as given below.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
5. print("Deleting some of the employee data")
6. del Employee["Name"]
7. del Employee["Company"]
8. print("printing the modified information ")
9. print(Employee)
10. print("Deleting the dictionary: Employee");
11. del Employee
12. print("Lets try to print it again ");
13. print(Employee)

Output:

<class 'dict'>
printing Employee data ....
{'Age': 29, 'Company': 'GOOGLE', 'Name': 'John', 'salary': 25000}

CMPINFOTECH pg. 8
Python Programming Dictionary CMP Infotech

Deleting some of the employee data


printing the modified information
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Lets try to print it again
Traceback (most recent call last):
File "list.py", line 13, in <module>
print(Employee)
NameError: name 'Employee' is not defined

Iterating Dictionary
A dictionary can be iterated using the for loop as given below.

Example 1
# for loop to print all the keys of a dictionary

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. for x in Employee:
3. print(x);

Output:

Name
Age
salary
Company

Example 2
#for loop to print all the values of the dictionary

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. for x in Employee:
3. print(Employee[x]);

Output:

CMPINFOTECH pg. 9
Python Programming Dictionary CMP Infotech

John
29
25000
GOOGLE

Example 3
#for loop to print the values of the dictionary by using values() method.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. for x in Employee.values():
3. print(x);

Output:

John
29
25000
GOOGLE
Example 4
#for loop to print the items of the dictionary by using items() method.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. for x in Employee.items():
3. print(x);

Output:

('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')

Summary:

Dictionaries in a programming language is a type of data-structure used to store


information connected in some way. Python Dictionary are defined into two
elements Keys and Values. Dictionaries do not store their information in any
particular order, so you may not get your information back in the same order you
entered it.

CMPINFOTECH pg. 10
Python Programming Dictionary CMP Infotech

 Keys will be a single element


 Values can be a list or list within a list, numbers, etc.
 More than one entry per key is not allowed ( no duplicate key is allowed)
 The values in the dictionary can be of any type while the keys must be immutable like
numbers, tuples or strings.
 Dictionary keys are case sensitive- Same key name but with the different case are
treated as different keys in Python dictionaries.

CMPINFOTECH pg. 11

You might also like