The document discusses Python dictionaries. Some key points:
- A dictionary in Python is an unordered collection of key-value pairs where keys must be unique and immutable, while values can be any data type.
- Dictionaries are created using curly braces {} and keys are separated from values with colons.
- Elements can be accessed, added, updated, and deleted using keys. Nested dictionaries are also supported.
- Common operations include creating, accessing, modifying dictionaries as well as nested dictionaries. User input can also be used to update dictionary values.
A dictionary is used to store player details like name, age, height and experience for a cricket team. Players under 19 are extracted to a new dictionary. 11 players are selected from the under 19 dictionary based on experience. The tallest player is chosen as the captain. The team and captain details are displayed.
- Dictionaries in Python are mutable and contain key-value pairs, with keys being unique and immutable.
- Common dictionary methods include keys(), values(), items(), get(), update(), pop(), popitem() etc.
- Dictionaries can be iterated over using for loops and sorted. Operations like merging, concatenation, checking presence of keys are also possible on dictionaries.
"Python Dictionary: The Key to Efficient Data Storage, Manipulation, and Vers...ZainabHaneen
A Python dictionary is a powerful data structure that stores key-value pairs. It's versatile, efficient, and widely used in Python programming for its simplicity and flexibility. Let's delve into a comprehensive description of Python dictionaries, covering their definition, syntax, operations, methods, use cases, and more.
### Definition:
A dictionary in Python is an unordered collection of items. Each item is a pair of a key and its corresponding value. Unlike sequences such as lists or tuples, dictionaries are indexed by keys, not by a range of numbers.
### Syntax:
Dictionaries are defined using curly braces `{}`. Each item in a dictionary is written as a key-value pair separated by a colon `:`. Keys are unique within a dictionary, while values can be of any data type, including integers, strings, lists, tuples, other dictionaries, or even functions.
Example:
```python
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
```
### Operations:
1. **Accessing Values:** You can access the value associated with a key using square brackets `[]`.
Example:
```python
print(my_dict['name']) # Output: John
```
2. **Updating Values:** You can update the value associated with a key by assigning a new value to that key.
Example:
```python
my_dict['age'] = 31
```
3. **Adding New Items:** You can add new key-value pairs to a dictionary by assigning a value to a new key.
Example:
```python
my_dict['gender'] = 'Male'
```
4. **Removing Items:** You can remove key-value pairs from a dictionary using the `del` keyword or the `pop()` method.
Example:
```python
del my_dict['city']
my_dict.pop('age')
```
### Methods:
Python provides several built-in methods to perform various operations on dictionaries:
1. `clear()`: Removes all items from the dictionary.
2. `copy()`: Returns a shallow copy of the dictionary.
3. `get(key[, default])`: Returns the value associated with the specified key, or a default value if the key is not found.
4. `items()`: Returns a view object that displays a list of a dictionary's key-value pairs.
5. `keys()`: Returns a view object that displays a list of the dictionary's keys.
6. `values()`: Returns a view object that displays a list of the dictionary's values.
7. `pop(key[, default])`: Removes the item with the specified key and returns its value. If the key is not found, it returns the default value.
8. `popitem()`: Removes and returns the last inserted key-value pair.
9. `update()`: Updates the dictionary with the key-value pairs from another dictionary or an iterable of key-value pairs.
### Use Cases:
1. **Storing Data:** Dictionaries are commonly used to store data in a structured format, especially when the data has associated labels or categories.
2. **Configuration Settings:** Dictionaries are useful for storing configuration settings in Python applications.
3. **Caching:** Dictionaries can be used to cache the results of expensive function calls for improved performance.
Python- Creating Dictionary,
Accessing and Modifying key: value Pairs in Dictionaries
Built-In Functions used on Dictionaries,
Dictionary Methods
Removing items from dictionary
This document provides an overview of functions and dictionaries in Python. It defines a function as reusable block of code that takes arguments, performs computations, and returns a result. Functions provide modularity and code reusability. The document outlines how to define functions using the def keyword, pass arguments, return values, and call functions. It also discusses function scopes, default argument values, and that functions without a return statement return None. The document then defines dictionaries as mutable containers that store key-value pairs, and describes how to access, update, and delete dictionary elements. It notes some properties of dictionary keys including no duplicate keys and that keys must be immutable. Finally, it lists some built-in functions and methods for working with dictionaries
This document contains a presentation on self-learning modules in Python. It discusses:
1. Assigning modules to different students for learning.
2. Modules, packages, and libraries as different ways to reuse code in Python. A module is a file with the .py extension, a package is a folder containing modules, and a library is a collection of packages.
3. The Python standard library contains built-in functions and modules that are part of the Python installation. Common modules discussed include math, random, and urllib.
The dictionary is a built-in Python data type that maps keys to values. It allows storing related data in key-value pairs. An example dictionary stores information about a college course with keys like 'branch', 'year', and values like 'aero', 'second'. Dictionaries have built-in methods like dict.keys() to access just the keys, dict.values() to access just the values, and dict.items() to access both in tuple pairs. The split() and join() string methods allow splitting or joining strings on a specified delimiter like a space, comma, or colon.
This document discusses Python dictionaries. It defines dictionaries as mappings between keys and values, where keys can be any immutable type like strings or numbers. It provides examples of creating empty dictionaries, adding items, accessing values by key, and built-in functions like len(), get(), pop(), keys(), update(), and del. It also discusses using dictionaries to count letter frequencies in strings and to parse text files. Advanced topics covered include translating strings using maketrans() and translate(), ignoring punctuation, and converting dictionaries to lists.
The document discusses tuples, lists, and dictionaries in Python. Tuples are immutable sequences that are created using parentheses. Lists are mutable sequences that can be modified using methods like append(). Dictionaries are collections of key-value pairs that are indexed by keys and allow for adding, updating and deleting elements. Both lists and tuples can be traversed using for loops, while dictionaries are traversed by their keys.
This document discusses dictionaries in Python. It defines dictionaries as mappings between keys and values, like lists but with the index as any immutable type rather than just integers. It demonstrates creating, accessing, updating, deleting items from dictionaries and various operations like getting keys/values, checking for keys, looping, and using dictionaries to count word frequencies in files.
this document consists of the introduction to python, how to install and run it, arithmetic operations, values and types (dictionaries, lists, tuples, strings, numbers, etc.) and the formal language and natural language
This document provides information about dictionaries in Python:
1. It defines a dictionary as an unordered collection of items where each item consists of a key and a value. Dictionaries are mutable but keys must be unique and immutable.
2. It explains how to create a dictionary by enclosing items in curly braces with keys and values separated by colons, and how to access values using the get() method or indexing with keys.
3. It discusses various ways to iterate through a dictionary using a for loop, update and modify dictionary elements, and delete elements using del, pop(), and clear().
4. It also covers built-in dictionary functions like len(), str(), type(), and various
The document provides an introduction and comparison of Python and C programming languages. Some key points:
- Python is an interpreted language while C needs compilation. Python makes program development faster.
- Variables, input/output, arrays, control structures like if/else, for loops work differently in Python compared to C.
- Python uses lists instead of arrays. Lists are mutable and support slicing.
- Strings are treated as character lists in Python.
- Functions are defined using def keyword in Python.
- The document also introduces sequences (strings, tuples, lists), dictionaries, and sets in Python - their usage and operations.
The document discusses various ways to convert between JSON and XML formats in Python. It describes using the json and xmltodict modules to serialize and deserialize between the two formats. Methods like json.loads(), json.dumps(), xmltodict.unparse() are used to convert between Python dictionaries and JSON/XML strings or files. Both string conversions and file conversions are demonstrated.
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
This document provides an introduction to learning Python. It discusses prerequisites for Python, basic Python concepts like variables, data types, operators, conditionals and loops. It also covers functions, files, classes and exceptions handling in Python. The document demonstrates these concepts through examples and exercises learners to practice char frequency counting and Caesar cipher encoding/decoding in Python. It encourages learners to practice more to master the language and provides additional learning resources.
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...Infopitaara
A feed water heater is a device used in power plants to preheat water before it enters the boiler. It plays a critical role in improving the overall efficiency of the power generation process, especially in thermal power plants.
🔧 Function of a Feed Water Heater:
It uses steam extracted from the turbine to preheat the feed water.
This reduces the fuel required to convert water into steam in the boiler.
It supports Regenerative Rankine Cycle, increasing plant efficiency.
🔍 Types of Feed Water Heaters:
Open Feed Water Heater (Direct Contact)
Steam and water come into direct contact.
Mixing occurs, and heat is transferred directly.
Common in low-pressure stages.
Closed Feed Water Heater (Surface Type)
Steam and water are separated by tubes.
Heat is transferred through tube walls.
Common in high-pressure systems.
⚙️ Advantages:
Improves thermal efficiency.
Reduces fuel consumption.
Lowers thermal stress on boiler components.
Minimizes corrosion by removing dissolved gases.
Ad
More Related Content
Similar to Dictionary in python Dictionary in python Dictionary in pDictionary in python ython (20)
Python- Creating Dictionary,
Accessing and Modifying key: value Pairs in Dictionaries
Built-In Functions used on Dictionaries,
Dictionary Methods
Removing items from dictionary
This document provides an overview of functions and dictionaries in Python. It defines a function as reusable block of code that takes arguments, performs computations, and returns a result. Functions provide modularity and code reusability. The document outlines how to define functions using the def keyword, pass arguments, return values, and call functions. It also discusses function scopes, default argument values, and that functions without a return statement return None. The document then defines dictionaries as mutable containers that store key-value pairs, and describes how to access, update, and delete dictionary elements. It notes some properties of dictionary keys including no duplicate keys and that keys must be immutable. Finally, it lists some built-in functions and methods for working with dictionaries
This document contains a presentation on self-learning modules in Python. It discusses:
1. Assigning modules to different students for learning.
2. Modules, packages, and libraries as different ways to reuse code in Python. A module is a file with the .py extension, a package is a folder containing modules, and a library is a collection of packages.
3. The Python standard library contains built-in functions and modules that are part of the Python installation. Common modules discussed include math, random, and urllib.
The dictionary is a built-in Python data type that maps keys to values. It allows storing related data in key-value pairs. An example dictionary stores information about a college course with keys like 'branch', 'year', and values like 'aero', 'second'. Dictionaries have built-in methods like dict.keys() to access just the keys, dict.values() to access just the values, and dict.items() to access both in tuple pairs. The split() and join() string methods allow splitting or joining strings on a specified delimiter like a space, comma, or colon.
This document discusses Python dictionaries. It defines dictionaries as mappings between keys and values, where keys can be any immutable type like strings or numbers. It provides examples of creating empty dictionaries, adding items, accessing values by key, and built-in functions like len(), get(), pop(), keys(), update(), and del. It also discusses using dictionaries to count letter frequencies in strings and to parse text files. Advanced topics covered include translating strings using maketrans() and translate(), ignoring punctuation, and converting dictionaries to lists.
The document discusses tuples, lists, and dictionaries in Python. Tuples are immutable sequences that are created using parentheses. Lists are mutable sequences that can be modified using methods like append(). Dictionaries are collections of key-value pairs that are indexed by keys and allow for adding, updating and deleting elements. Both lists and tuples can be traversed using for loops, while dictionaries are traversed by their keys.
This document discusses dictionaries in Python. It defines dictionaries as mappings between keys and values, like lists but with the index as any immutable type rather than just integers. It demonstrates creating, accessing, updating, deleting items from dictionaries and various operations like getting keys/values, checking for keys, looping, and using dictionaries to count word frequencies in files.
this document consists of the introduction to python, how to install and run it, arithmetic operations, values and types (dictionaries, lists, tuples, strings, numbers, etc.) and the formal language and natural language
This document provides information about dictionaries in Python:
1. It defines a dictionary as an unordered collection of items where each item consists of a key and a value. Dictionaries are mutable but keys must be unique and immutable.
2. It explains how to create a dictionary by enclosing items in curly braces with keys and values separated by colons, and how to access values using the get() method or indexing with keys.
3. It discusses various ways to iterate through a dictionary using a for loop, update and modify dictionary elements, and delete elements using del, pop(), and clear().
4. It also covers built-in dictionary functions like len(), str(), type(), and various
The document provides an introduction and comparison of Python and C programming languages. Some key points:
- Python is an interpreted language while C needs compilation. Python makes program development faster.
- Variables, input/output, arrays, control structures like if/else, for loops work differently in Python compared to C.
- Python uses lists instead of arrays. Lists are mutable and support slicing.
- Strings are treated as character lists in Python.
- Functions are defined using def keyword in Python.
- The document also introduces sequences (strings, tuples, lists), dictionaries, and sets in Python - their usage and operations.
The document discusses various ways to convert between JSON and XML formats in Python. It describes using the json and xmltodict modules to serialize and deserialize between the two formats. Methods like json.loads(), json.dumps(), xmltodict.unparse() are used to convert between Python dictionaries and JSON/XML strings or files. Both string conversions and file conversions are demonstrated.
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
This document provides an introduction to learning Python. It discusses prerequisites for Python, basic Python concepts like variables, data types, operators, conditionals and loops. It also covers functions, files, classes and exceptions handling in Python. The document demonstrates these concepts through examples and exercises learners to practice char frequency counting and Caesar cipher encoding/decoding in Python. It encourages learners to practice more to master the language and provides additional learning resources.
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...Infopitaara
A feed water heater is a device used in power plants to preheat water before it enters the boiler. It plays a critical role in improving the overall efficiency of the power generation process, especially in thermal power plants.
🔧 Function of a Feed Water Heater:
It uses steam extracted from the turbine to preheat the feed water.
This reduces the fuel required to convert water into steam in the boiler.
It supports Regenerative Rankine Cycle, increasing plant efficiency.
🔍 Types of Feed Water Heaters:
Open Feed Water Heater (Direct Contact)
Steam and water come into direct contact.
Mixing occurs, and heat is transferred directly.
Common in low-pressure stages.
Closed Feed Water Heater (Surface Type)
Steam and water are separated by tubes.
Heat is transferred through tube walls.
Common in high-pressure systems.
⚙️ Advantages:
Improves thermal efficiency.
Reduces fuel consumption.
Lowers thermal stress on boiler components.
Minimizes corrosion by removing dissolved gases.
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...Infopitaara
A Boiler Feed Pump (BFP) is a critical component in thermal power plants. It supplies high-pressure water (feedwater) to the boiler, ensuring continuous steam generation.
⚙️ How a Boiler Feed Pump Works
Water Collection:
Feedwater is collected from the deaerator or feedwater tank.
Pressurization:
The pump increases water pressure using multiple impellers/stages in centrifugal types.
Discharge to Boiler:
Pressurized water is then supplied to the boiler drum or economizer section, depending on design.
🌀 Types of Boiler Feed Pumps
Centrifugal Pumps (most common):
Multistage for higher pressure.
Used in large thermal power stations.
Positive Displacement Pumps (less common):
For smaller or specific applications.
Precise flow control but less efficient for large volumes.
🛠️ Key Operations and Controls
Recirculation Line: Protects the pump from overheating at low flow.
Throttle Valve: Regulates flow based on boiler demand.
Control System: Often automated via DCS/PLC for variable load conditions.
Sealing & Cooling Systems: Prevent leakage and maintain pump health.
⚠️ Common BFP Issues
Cavitation due to low NPSH (Net Positive Suction Head).
Seal or bearing failure.
Overheating from improper flow or recirculation.
We introduce the Gaussian process (GP) modeling module developed within the UQLab software framework. The novel design of the GP-module aims at providing seamless integration of GP modeling into any uncertainty quantification workflow, as well as a standalone surrogate modeling tool. We first briefly present the key mathematical tools on the basis of GP modeling (a.k.a. Kriging), as well as the associated theoretical and computational framework. We then provide an extensive overview of the available features of the software and demonstrate its flexibility and user-friendliness. Finally, we showcase the usage and the performance of the software on several applications borrowed from different fields of engineering. These include a basic surrogate of a well-known analytical benchmark function; a hierarchical Kriging example applied to wind turbine aero-servo-elastic simulations and a more complex geotechnical example that requires a non-stationary, user-defined correlation function. The GP-module, like the rest of the scientific code that is shipped with UQLab, is open source (BSD license).
Concept of Problem Solving, Introduction to Algorithms, Characteristics of Algorithms, Introduction to Data Structure, Data Structure Classification (Linear and Non-linear, Static and Dynamic, Persistent and Ephemeral data structures), Time complexity and Space complexity, Asymptotic Notation - The Big-O, Omega and Theta notation, Algorithmic upper bounds, lower bounds, Best, Worst and Average case analysis of an Algorithm, Abstract Data Types (ADT)
In tube drawing process, a tube is pulled out through a die and a plug to reduce its diameter and thickness as per the requirement. Dimensional accuracy of cold drawn tubes plays a vital role in the further quality of end products and controlling rejection in manufacturing processes of these end products. Springback phenomenon is the elastic strain recovery after removal of forming loads, causes geometrical inaccuracies in drawn tubes. Further, this leads to difficulty in achieving close dimensional tolerances. In the present work springback of EN 8 D tube material is studied for various cold drawing parameters. The process parameters in this work include die semi-angle, land width and drawing speed. The experimentation is done using Taguchi’s L36 orthogonal array, and then optimization is done in data analysis software Minitab 17. The results of ANOVA shows that 15 degrees die semi-angle,5 mm land width and 6 m/min drawing speed yields least springback. Furthermore, optimization algorithms named Particle Swarm Optimization (PSO), Simulated Annealing (SA) and Genetic Algorithm (GA) are applied which shows that 15 degrees die semi-angle, 10 mm land width and 8 m/min drawing speed results in minimal springback with almost 10.5 % improvement. Finally, the results of experimentation are validated with Finite Element Analysis technique using ANSYS.
This paper proposes a shoulder inverse kinematics (IK) technique. Shoulder complex is comprised of the sternum, clavicle, ribs, scapula, humerus, and four joints.
Sorting Order and Stability in Sorting.
Concept of Internal and External Sorting.
Bubble Sort,
Insertion Sort,
Selection Sort,
Quick Sort and
Merge Sort,
Radix Sort, and
Shell Sort,
External Sorting, Time complexity analysis of Sorting Algorithms.
Fluid mechanics is the branch of physics concerned with the mechanics of fluids (liquids, gases, and plasmas) and the forces on them. Originally applied to water (hydromechanics), it found applications in a wide range of disciplines, including mechanical, aerospace, civil, chemical, and biomedical engineering, as well as geophysics, oceanography, meteorology, astrophysics, and biology.
It can be divided into fluid statics, the study of various fluids at rest, and fluid dynamics.
Fluid statics, also known as hydrostatics, is the study of fluids at rest, specifically when there's no relative motion between fluid particles. It focuses on the conditions under which fluids are in stable equilibrium and doesn't involve fluid motion.
Fluid kinematics is the branch of fluid mechanics that focuses on describing and analyzing the motion of fluids, such as liquids and gases, without considering the forces that cause the motion. It deals with the geometrical and temporal aspects of fluid flow, including velocity and acceleration. Fluid dynamics, on the other hand, considers the forces acting on the fluid.
Fluid dynamics is the study of the effect of forces on fluid motion. It is a branch of continuum mechanics, a subject which models matter without using the information that it is made out of atoms; that is, it models matter from a macroscopic viewpoint rather than from microscopic.
Fluid mechanics, especially fluid dynamics, is an active field of research, typically mathematically complex. Many problems are partly or wholly unsolved and are best addressed by numerical methods, typically using computers. A modern discipline, called computational fluid dynamics (CFD), is devoted to this approach. Particle image velocimetry, an experimental method for visualizing and analyzing fluid flow, also takes advantage of the highly visual nature of fluid flow.
Fundamentally, every fluid mechanical system is assumed to obey the basic laws :
Conservation of mass
Conservation of energy
Conservation of momentum
The continuum assumption
For example, the assumption that mass is conserved means that for any fixed control volume (for example, a spherical volume)—enclosed by a control surface—the rate of change of the mass contained in that volume is equal to the rate at which mass is passing through the surface from outside to inside, minus the rate at which mass is passing from inside to outside. This can be expressed as an equation in integral form over the control volume.
The continuum assumption is an idealization of continuum mechanics under which fluids can be treated as continuous, even though, on a microscopic scale, they are composed of molecules. Under the continuum assumption, macroscopic (observed/measurable) properties such as density, pressure, temperature, and bulk velocity are taken to be well-defined at "infinitesimal" volume elements—small in comparison to the characteristic length scale of the system, but large in comparison to molecular length scale
2. What is a Dictionary in Python?
• A Dictionary in Python is the unordered, and changeable collection of data values that holds
key-value pairs.
• Each key-value pair in the dictionary maps the key to its associated value.
• Python Dictionary is classified into two elements: Keys and Values.
• Keys will be a single element.
• Values can be a list or list within a list, numbers, etc.
3. Cont..
• Dictionary is ordered or unordered?
• As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
• When we say that dictionaries are ordered, it means that the items have a defined order,
and that order will not change.
• Unordered means that the items does not have a defined order, you cannot refer to
an item by using an index.
• Dictionary is Changeable:
• Dictionaries are changeable, meaning that we can change, add or remove items
after the dictionary has been created.
• Duplicates Not Allowed in dictionary:
• Dictionaries cannot have two items with the same key
4. How to Create a Dictionary in Python?
• Dictionary is created with curly brackets, inside these curly brackets, keys and values are declared. Each key is
separated from its value by a colon (:), while commas separate each element.
• A Dictionary in python is declared by enclosing a comma-separated list of key-value pairs using curly braces({}).
• Dictionaries are used to store data values in key:value pairs.
#Creating an empty dictionary
d = {}
#Creating an empty dictionary with the dict function
d = dict()
5. Cont…
# Initializing a dictionary with values
a = {"a":1 ,"b":2}
b = {'fruit': 'apple', ‘color': ‘red’}
c = {'name': ‘Suchith', 'age’: 20}
d = {'name': ‘Ishanth’, ‘sem’: [1,2,3,7]}
e = {‘branch’:‘CSE’, ‘course’:[‘c’,’java’,’python’]}
f = {'a':1, 'b':2, 'c':3, 'd’:2}
# For Sequence of Key-Value Pairs
g = dict([(1, ‘Apple'), (2, 'Orange'), (3, 'Kiwi')])
6. Properties of Dictionary Keys
• Keys must be unique: 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
cases are treated as different keys in Python dictionaries.
7. How to Access Python Dictionary items?
• Since the dictionary is an unordered collection, we can access the values using their
keys.
• It can be done by placing the key in the square brackets or using the get function.
• Ex: Dname[key] or Dname.get(key)
• If we access a non-existing one,
• The get function returns none.
• The key inside a square brackets method throw an error.
9. Cont..
# Accessing dictionary items
>>> a = {'name': 'Kevin', 'age': 25, 'job': 'Developer’}
>>> len(a) #length of dictionary
3
# using get()
>>> print("Name : ", a.get('name’))
Name : Kevin
>>> print("Age : ", a.get('age’))
Age : 25
>>> print("Job : ", a.get('job’))
Job : Developer
10. Insert and Update Dictionary items
• Remember, dicts are mutable, so you can insert or update any element at any point in time. Use the below
syntax to insert or update values.
DName[key] = value
• If a key is present, it updates the value. If DName does not have the key, then it inserts the new one with
the given.
>>> da = {'name': 'Kevin', 'age': 25}
# Print Elements
>>> print("Items : ", da)
Items : {'name': 'Kevin', 'age': 25}
# Add an Item
>>> da['job'] = 'Programmer'
>>> print("nItems : ", da)
Items : {'name': 'Kevin', 'age': 25, 'job': 'Programmer’}
# Update an Item
>>> da['name'] = 'Python'
>>> print("nItems : ", da)
Items : {'name': 'Python', 'age': 25, 'job': 'Programmer'}
11. Methods in Python Dictionary
Functions Description
clear() Removes all Items
copy() Returns Shallow Copy of a Dictionary
fromkeys() Creates a dictionary from the given sequence
get() Find the value of a key
items() Returns view of dictionary’s (key, value) pair
keys() Prints the keys
popitem() Remove the last element of the dictionary
setdefault() Inserts Key With a Value if Key is not Present
pop() Removes and returns element having given key
values() Returns view of all values in the dictionary
update() Updates the Dictionary
12. Cont..
keys(): The keys() method returns a list of keys in a Python dictionary.
>>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’}
>>> d.keys()
dict_keys(['name', 'age', 'job'])
values(): The values() method returns a list of values in the dictionary.
>>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’}
>>> dict4.values()
dict_values(['Python', 25, 'Programmer'])
13. Cont..
items(): This method returns a list of key-value pairs.
>>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’}
>>> d.items()
dict_items([('name','Python'),('age',25),('job','Programmer')])
get(): It takes one to two arguments. While the first is the key to search for,
the second is the value to return if the key isn’t found. The default value for
this second argument is None.
>>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’}
>>> d.get('job')
'Programmer'
>>> d.get("role")
>>> d.get("role","Not Present")
'Not Present'
14. Cont..
copy(): Python dictionary method copy() returns a shallow copy of the dictionary.
>>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’}
>>> d2=d.copy()
>>> d
{'name': 'Python', 'age': 25, 'job': 'Programmer’}
>>> d2
{'name': 'Python', 'age': 25, 'job': 'Programmer’}
>>> id(d)
3218144153792
>>> id(d2)
3218150637248
15. Cont..
pop(): This method is used to remove and display an item from the dictionary. It takes
one or two arguments. The first is the key to be deleted, while the second is the value
that’s returned if the key isn’t found.
>>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’}
>>> d.pop("age")
25
>>> d
{'name': 'Python', 'job': 'Programmer'}
>>> d.pop("role")
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
d.pop("role")
KeyError: 'role'
>>> d.pop("role",-1)
-1
16. Cont..
popitem():The popitem() method removes and returns the item that was last inserted into
the dictionary.
>>> d ={'name': 'Python', 'job': 'Programmer’, 'age’: 26}
>>> d.popitem()
('age', 26)
fromkeys(): Python dictionary method fromkeys() creates a new dictionary
with keys from seq and values set to value.
>>> d=fromkeys({1,2,3,4,7},0)
>>> d
{1: 0, 2: 0, 3: 0, 4: 0, 7: 0}
>>> seq = ('name', 'age', ‘job’)
>>> d2 = d2.fromkeys(seq)
>>> d2
{'age': None, 'name': None, ‘job': None}
17. Cont..
update():The update() method takes another dictionary as an argument. Then it updates
the dictionary to hold values from the other dictionary that it doesn’t already.
>>> d1 ={'name': 'Python', 'job': 'Programmer’}
>>> d2 ={'age’: 26}
>>> d1.update(d2)
>>> print(d1)
{'name': 'python', 'job': 'programmer', 'age': 25}
>>> d1 ={'name': 'Python', 'job': 'Programmer’}
>>> d2 ={'age’: 26, 'name’: ‘Java'}
>>> d1.update(d2)
>>> print(d1)
{'name’: ‘Java', 'job': 'programmer', 'age': 25}
clear(): Removes all elements of dictionary.
>>> d ={'name': 'Python', 'job': 'Programmer’, 'age’: 26}
>>> d.clear()
{}
18. Cont..
setdefault():
Returns the value of the specified key in the dictionary. If the key not found, then it adds
the key with the specified defaultvalue. If the defaultvalue is not specified then it set None value.
Syntax:
dict.setdefault(key, defaultValue)
Ex:
romanNums = {'I':1, 'II':2, 'III':3}
romanNums.setdefault('IV')
print(romanNums)
{'I': 1, 'II': 2, 'III': 3, 'IV': None}
romanNums.setdefault('VI', 4)
print(romanNums)
{'I': 1, 'II': 2, 'III': 3, 'IV': 4}
19. Iterating Dictionary
• A dictionary can be iterated using for loop as given below.
# for loop to print all the keys of a dictionary
Employee = {"Name": “Kiran",
"Age": 29,
"salary":25000,
"Company":"GOOGLE"}
for i in Employee:
print(i)
Output:
Name
Age
salary
Company
20. Iterating Dictionary
# for loop to print all the keys of a dictionary
Employee = {"Name": “Kiran", "Age": 29, "salary":25000,
"Company":"GOOGLE"}
Output:
Kiran
29
25000
GOOGLE
for i in Employee.values():
print(i)
for i in Employee:
print(Employee[i])
Output:
Kiran
29
25000
GOOGLE
21. Iterating Dictionary
• A dictionary can be iterated using for loop as given below.
# for loop to print all the keys of a dictionary
Employee = {"Name": “Kiran",
"Age": 29,
"salary":25000,
"Company":"GOOGLE"}
for i in Employee.items():
print(i)
Output:
('Name', 'Kiran')
('Age', 29)
('salary', 25000)
('Company',
'GOOGLE')
22. Difference between List and Dictionary in Python
Comparison
Parameter
List Dictionary
Definition Collection of various elements just like an array.
Collection of elements in the hashed structure as
key-value pairs
Syntax
Placing all the elements inside square brackets [],
separated by commas(,)
Placing all key-value pairs inside curly brackets({}),
separated by a comma. Also, each key and pair is
separated by a semi-colon (:)
Index type Indices are integer values starts from value 0 The keys in the dictionary are of any given data type
Mode of Access We can access the elements using the index value We can access the elements using the keys
Order of
Elements
The default order of elements is always
maintained
No guarantee of maintaining the order
Mutability Lists are mutable in nature
Dictionaries are mutable, but keys do not allow
duplicates
Creation List object is created using list() function Dictionary object is created using dict() function
Sort()
Sort() method sorts the elements in ascending or
descending order
Sort() method sorts the keys in the dictionary by
default
Count()
Count() methods returns the number of elements
appeared in list
Count() method does not exists in dictionation
Reverse() Reverse() method reverse the list elements
Dictionary items cannot be reversed as they are the
key-value pairs
23. Write a Python program to check whether a given key already exists in a
dictionary.
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
key=int(input(“enter key element to be searched”))
if n in d:
print("key present")
else:
print("Key not present")
24. Write a program to count the number of occurrences of character in a
string.
x = input("Enter a String: ")
count = {}
for ch in x:
count.setdefault(ch, 0)
count[ch] = count[ch] + 1
print(count)
Output:
Enter a String: Kannada
{'K': 1, 'a': 3, 'n': 2, 'd': 1}
25. Write a Python script to print a dictionary where the keys are numbers
between 1 and 15 (both included) and the values are square of keys.
d=dict()
for x in range(1,16):
d[x]=x**2
print(d)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49,
8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169,
14: 196, 15: 225}