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
Lists, tuples, and dictionaries are common data structures in Python. Lists are mutable sequences that are defined using square brackets. Tuples are immutable sequences defined using parentheses. Dictionaries store key-value pairs within curly braces, with unique keys. These data structures support operations like indexing, slicing, length checking, membership testing, and iteration.
These are the slides of the second part of this multi-part series, from Learn Python Den Haag meetup group. It covers List comprehensions, Dictionary comprehensions and functions.
The document discusses object-oriented programming in Python. It defines key OOP concepts like classes, objects, and methods. It provides examples of defining classes and methods in Python. It also covers inheritance, polymorphism, and data abstraction in OOP. Database programming in Python is also discussed, including connecting to databases and performing CRUD operations using the Python DB API.
The document provides an overview of object-oriented programming concepts in Python including defining classes, inheritance, methods, and data structures. Some key points:
- Classes define user-created data types that bundle together data (attributes) and functions (methods) that work with that data. Objects are instances of classes.
- Methods are defined within classes and must have "self" as the first argument to access attributes. The __init__ method serves as a constructor.
- Inheritance allows subclasses to extend existing classes, redefining or calling parent methods.
- Python supports lists, tuples, dictionaries, sets and other data structures that can be used to store and organize data. Lists are mutable while tuples are immutable.
This document provides an overview of many common Python programming concepts including variables, strings, lists, tuples, dictionaries, conditionals, functions, classes, files and exceptions. It demonstrates how to store and manipulate different data types, write conditional logic, define reusable blocks of code as functions, organize code into classes and objects, read from and write to files, and handle errors through exceptions. Key examples include creating and accessing elements in lists and dictionaries, writing conditional statements, defining and calling functions, creating classes and using inheritance, opening and reading/writing files, and using try/except blocks to catch errors.
The Ring programming language version 1.5.1 book - Part 32 of 180Mahmoud Samir Fayed
油
The document provides documentation on Ring programming language functions and features. It summarizes the use of various functions in the stdlib.ring library including puts(), print(), print2Str(), getstring(), getnumber(), apppath(), justfilepath(), justfilename(), value(), times(), map(), filter(), split(), splitmany(), newlist(), capitalized(), isspecial(), isvowel(), linecount(), factorial(), fibonacci(), isprime(), and sign(). Examples are given to demonstrate the usage of each function.
The Ring programming language version 1.9 book - Part 42 of 210Mahmoud Samir Fayed
油
The document discusses Ring programming language functions from the stdlib module for input/output, string manipulation, lists, files and math operations. Functions described include print(), getsring(), split(), capitalized(), factorial(), fibonacci(), isprime() and more. Examples are provided to demonstrate how to use each function.
The Ring programming language version 1.10 book - Part 43 of 212Mahmoud Samir Fayed
油
The document provides examples of using various functions in Ring's standard library (stdlib) for input/output, string manipulation, lists, and more. Key functions discussed include puts(), print(), print2Str(), getString(), getNumber(), appPath(), justFilePath(), justFileName(), value(), times(), map(), filter(), split(), splitMany(), newList(), and capitalized(). Examples are given to demonstrate how each function works and what it returns. The document serves as a reference for the main functions available in Ring's standard library.
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 Ring programming language version 1.7 book - Part 37 of 196Mahmoud Samir Fayed
油
The document provides examples of using various functions in Ring to add, get, and modify methods and attributes of objects. It demonstrates how to add methods to classes using addmethod(), get attribute values using getattribute(), set attribute values using setattribute(), share methods between classes using mergemethods(), and get the package name of the latest import using packagename(). Examples are given for each function to illustrate their usage.
This document contains notes from a series of tips and quirks related to Ruby programming. It covers topics like local variables in different Ruby versions, differences between strings and symbols, using modules and classes, responding to super, object counting, finalizers, and calling procs. The document provides code examples to demonstrate various Ruby language features and behaviors.
The document provides an overview of common Python data structures and programming concepts including:
- Strings, variables, and concatenation for combining strings
- Lists for storing ordered sets of items that can be accessed by index or looped through
- Tuples for storing immutable sets of items similar to lists
- Dictionaries for storing connections between keys and values in non-ordered key-value pairs
- Common operations for each like appending, inserting, removing, sorting, and slicing items
It also covers conditional statements, functions, files, exceptions, classes and objects, user input/output, and while and for loops for iteration. The goal is to introduce fundamental Python programming concepts and data handling techniques.
This document provides an overview of Python lists:
- Lists store a series of items in a particular order and allow you to access items using an index or loop through the items.
- You can add and remove items from lists, sort lists, loop through lists to print or modify items, and access items by index.
- Common list operations include appending items, inserting items, removing items, sorting lists, finding the length of a list, and accessing items by index. Lists provide a powerful way to organize and work with sets of data in Python.
This document provides an overview of Python lists:
- Lists store a series of items in a particular order and allow you to access items using an index or loop through the items.
- You can add and remove items from lists, sort lists, loop through lists to print or modify items, and access items by index.
- Common list operations include appending to add an item, inserting to add an item at a specific index, removing items, sorting lists, finding the length of a list, and accessing items by index.
The document provides an overview of common Python data structures and programming concepts including:
- Strings, variables, and concatenation for combining strings
- Lists for storing ordered sets of items that can be accessed by index or looped through
- Tuples for storing immutable sets of items similar to lists
- Dictionaries for storing connections between keys and values in non-ordered key-value pairs
- Common operations for each like appending, inserting, removing, sorting, and slicing items
It also covers conditional statements, functions, files, exceptions, classes and objects, user input/output, and while and for loops for iteration. The goal is to introduce fundamental Python programming concepts and data structures.
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.
This document discusses functions and methods in Python. It defines functions and methods, and explains the differences between them. It provides examples of defining and calling functions, returning values from functions, and passing arguments to functions. It also covers topics like local and global variables, function decorators, generators, modules, and lambda functions.
The document provides an overview of common Python data structures and programming concepts including variables, strings, lists, tuples, dictionaries, conditionals, functions, files, classes, and more. It includes examples of how to define, access, modify, loop through, and perform operations on each type of data structure. Key points covered include using lists to store ordered sets of items, dictionaries to store connections between pieces of information as key-value pairs, and classes to define custom object types with attributes and methods.
The document provides an overview of Python lists:
- Lists allow you to store sets of information in a particular order and are one of Python's most powerful features.
- You can define lists using square brackets and commas, and use plural names for lists to make code more readable. Lists can contain millions of items.
- Lists allow adding, inserting, removing, sorting, and accessing elements by their position or value using various list methods like append(), insert(), remove(), sort(), and indexing.
- Loops like for loops efficiently iterate through lists to work with each element.
Beginners python cheat sheet - Basic knowledge O T
油
The document provides an overview of common Python data structures and programming concepts including variables, strings, lists, tuples, dictionaries, conditionals, functions, files, classes, and more. It includes examples of how to define, access, modify, loop through, and perform operations on each type of data structure. Key points covered include using lists to store ordered sets of items, dictionaries to store connections between pieces of information as key-value pairs, and classes to define custom object types with attributes and methods.
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.
Python- Creating Dictionary,
Accessing and Modifying key: value Pairs in Dictionaries
Built-In Functions used on Dictionaries,
Dictionary Methods
Removing items from dictionary
The Ring programming language version 1.7 book - Part 35 of 196Mahmoud Samir Fayed
油
The document contains documentation for the Ring programming language. It describes a Ring class that stores information about objects, including their name, symbol, and position. For each object, it lists these attributes. It also contains descriptions of using self and this to reference attributes and methods from within classes.
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...Yashpatel821746
油
This document contains 14 programming questions in Python with solutions. The questions cover a range of Python topics including file handling, classes and objects, functions, exception handling, matrices, and GUI programming using Tkinter. Tkinter widgets like buttons, checkboxes, canvases, entries, frames, listboxes, menus, radiobuttons, scrollbars are demonstrated. Other concepts covered include lambda functions, filters, dictionaries, lists, path handling functions like split, join, and normath, logging and log file rotation.
APM People Interest Network Conference 2025
-Autonomy, Teams and Tension: Projects under stress
-Tim Lyons
-The neurological levels of
team-working: Harmony and tensions
With a background in projects spanning more than 40 years, Tim Lyons specialised in the delivery of large, complex, multi-disciplinary programmes for clients including Crossrail, Network Rail, ExxonMobil, Siemens and in patent development. His first career was in broadcasting, where he designed and built commercial radio station studios in Manchester, Cardiff and Bristol, also working as a presenter and programme producer. Tim now writes and presents extensively on matters relating to the human and neurological aspects of projects, including communication, ethics and coaching. He holds a Masters degree in NLP, is an NLP Master Practitioner and International Coach. He is the Deputy Lead for APMs People Interest Network.
Session | The Neurological Levels of Team-working: Harmony and Tensions
Understanding how teams really work at conscious and unconscious levels is critical to a harmonious workplace. This session uncovers what those levels are, how to use them to detect and avoid tensions and how to smooth the management of change by checking you have considered all of them.
The Ring programming language version 1.9 book - Part 42 of 210Mahmoud Samir Fayed
油
The document discusses Ring programming language functions from the stdlib module for input/output, string manipulation, lists, files and math operations. Functions described include print(), getsring(), split(), capitalized(), factorial(), fibonacci(), isprime() and more. Examples are provided to demonstrate how to use each function.
The Ring programming language version 1.10 book - Part 43 of 212Mahmoud Samir Fayed
油
The document provides examples of using various functions in Ring's standard library (stdlib) for input/output, string manipulation, lists, and more. Key functions discussed include puts(), print(), print2Str(), getString(), getNumber(), appPath(), justFilePath(), justFileName(), value(), times(), map(), filter(), split(), splitMany(), newList(), and capitalized(). Examples are given to demonstrate how each function works and what it returns. The document serves as a reference for the main functions available in Ring's standard library.
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 Ring programming language version 1.7 book - Part 37 of 196Mahmoud Samir Fayed
油
The document provides examples of using various functions in Ring to add, get, and modify methods and attributes of objects. It demonstrates how to add methods to classes using addmethod(), get attribute values using getattribute(), set attribute values using setattribute(), share methods between classes using mergemethods(), and get the package name of the latest import using packagename(). Examples are given for each function to illustrate their usage.
This document contains notes from a series of tips and quirks related to Ruby programming. It covers topics like local variables in different Ruby versions, differences between strings and symbols, using modules and classes, responding to super, object counting, finalizers, and calling procs. The document provides code examples to demonstrate various Ruby language features and behaviors.
The document provides an overview of common Python data structures and programming concepts including:
- Strings, variables, and concatenation for combining strings
- Lists for storing ordered sets of items that can be accessed by index or looped through
- Tuples for storing immutable sets of items similar to lists
- Dictionaries for storing connections between keys and values in non-ordered key-value pairs
- Common operations for each like appending, inserting, removing, sorting, and slicing items
It also covers conditional statements, functions, files, exceptions, classes and objects, user input/output, and while and for loops for iteration. The goal is to introduce fundamental Python programming concepts and data handling techniques.
This document provides an overview of Python lists:
- Lists store a series of items in a particular order and allow you to access items using an index or loop through the items.
- You can add and remove items from lists, sort lists, loop through lists to print or modify items, and access items by index.
- Common list operations include appending items, inserting items, removing items, sorting lists, finding the length of a list, and accessing items by index. Lists provide a powerful way to organize and work with sets of data in Python.
This document provides an overview of Python lists:
- Lists store a series of items in a particular order and allow you to access items using an index or loop through the items.
- You can add and remove items from lists, sort lists, loop through lists to print or modify items, and access items by index.
- Common list operations include appending to add an item, inserting to add an item at a specific index, removing items, sorting lists, finding the length of a list, and accessing items by index.
The document provides an overview of common Python data structures and programming concepts including:
- Strings, variables, and concatenation for combining strings
- Lists for storing ordered sets of items that can be accessed by index or looped through
- Tuples for storing immutable sets of items similar to lists
- Dictionaries for storing connections between keys and values in non-ordered key-value pairs
- Common operations for each like appending, inserting, removing, sorting, and slicing items
It also covers conditional statements, functions, files, exceptions, classes and objects, user input/output, and while and for loops for iteration. The goal is to introduce fundamental Python programming concepts and data structures.
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.
This document discusses functions and methods in Python. It defines functions and methods, and explains the differences between them. It provides examples of defining and calling functions, returning values from functions, and passing arguments to functions. It also covers topics like local and global variables, function decorators, generators, modules, and lambda functions.
The document provides an overview of common Python data structures and programming concepts including variables, strings, lists, tuples, dictionaries, conditionals, functions, files, classes, and more. It includes examples of how to define, access, modify, loop through, and perform operations on each type of data structure. Key points covered include using lists to store ordered sets of items, dictionaries to store connections between pieces of information as key-value pairs, and classes to define custom object types with attributes and methods.
The document provides an overview of Python lists:
- Lists allow you to store sets of information in a particular order and are one of Python's most powerful features.
- You can define lists using square brackets and commas, and use plural names for lists to make code more readable. Lists can contain millions of items.
- Lists allow adding, inserting, removing, sorting, and accessing elements by their position or value using various list methods like append(), insert(), remove(), sort(), and indexing.
- Loops like for loops efficiently iterate through lists to work with each element.
Beginners python cheat sheet - Basic knowledge O T
油
The document provides an overview of common Python data structures and programming concepts including variables, strings, lists, tuples, dictionaries, conditionals, functions, files, classes, and more. It includes examples of how to define, access, modify, loop through, and perform operations on each type of data structure. Key points covered include using lists to store ordered sets of items, dictionaries to store connections between pieces of information as key-value pairs, and classes to define custom object types with attributes and methods.
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.
Python- Creating Dictionary,
Accessing and Modifying key: value Pairs in Dictionaries
Built-In Functions used on Dictionaries,
Dictionary Methods
Removing items from dictionary
The Ring programming language version 1.7 book - Part 35 of 196Mahmoud Samir Fayed
油
The document contains documentation for the Ring programming language. It describes a Ring class that stores information about objects, including their name, symbol, and position. For each object, it lists these attributes. It also contains descriptions of using self and this to reference attributes and methods from within classes.
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...Yashpatel821746
油
This document contains 14 programming questions in Python with solutions. The questions cover a range of Python topics including file handling, classes and objects, functions, exception handling, matrices, and GUI programming using Tkinter. Tkinter widgets like buttons, checkboxes, canvases, entries, frames, listboxes, menus, radiobuttons, scrollbars are demonstrated. Other concepts covered include lambda functions, filters, dictionaries, lists, path handling functions like split, join, and normath, logging and log file rotation.
APM People Interest Network Conference 2025
-Autonomy, Teams and Tension: Projects under stress
-Tim Lyons
-The neurological levels of
team-working: Harmony and tensions
With a background in projects spanning more than 40 years, Tim Lyons specialised in the delivery of large, complex, multi-disciplinary programmes for clients including Crossrail, Network Rail, ExxonMobil, Siemens and in patent development. His first career was in broadcasting, where he designed and built commercial radio station studios in Manchester, Cardiff and Bristol, also working as a presenter and programme producer. Tim now writes and presents extensively on matters relating to the human and neurological aspects of projects, including communication, ethics and coaching. He holds a Masters degree in NLP, is an NLP Master Practitioner and International Coach. He is the Deputy Lead for APMs People Interest Network.
Session | The Neurological Levels of Team-working: Harmony and Tensions
Understanding how teams really work at conscious and unconscious levels is critical to a harmonious workplace. This session uncovers what those levels are, how to use them to detect and avoid tensions and how to smooth the management of change by checking you have considered all of them.
Digital Tools with AI for e-Content Development.pptxDr. Sarita Anand
油
This ppt is useful for not only for B.Ed., M.Ed., M.A. (Education) or any other PG level students or Ph.D. scholars but also for the school, college and university teachers who are interested to prepare an e-content with AI for their students and others.
Prelims of Kaun TALHA : a Travel, Architecture, Lifestyle, Heritage and Activism quiz, organized by Conquiztadors, the Quiz society of Sri Venkateswara College under their annual quizzing fest El Dorado 2025.
How to Setup WhatsApp in Odoo 17 - Odoo 際際滷sCeline George
油
Integrate WhatsApp into Odoo using the WhatsApp Business API or third-party modules to enhance communication. This integration enables automated messaging and customer interaction management within Odoo 17.
How to Configure Flexible Working Schedule in Odoo 18 EmployeeCeline George
油
In this slide, well discuss on how to configure flexible working schedule in Odoo 18 Employee module. In Odoo 18, the Employee module offers powerful tools to configure and manage flexible working schedules tailored to your organization's needs.
Finals of Kaun TALHA : a Travel, Architecture, Lifestyle, Heritage and Activism quiz, organized by Conquiztadors, the Quiz society of Sri Venkateswara College under their annual quizzing fest El Dorado 2025.
How to use Init Hooks in Odoo 18 - Odoo 際際滷sCeline George
油
In this slide, well discuss on how to use Init Hooks in Odoo 18. In Odoo, Init Hooks are essential functions specified as strings in the __init__ file of a module.
Database population in Odoo 18 - Odoo slidesCeline George
油
In this slide, well discuss the database population in Odoo 18. In Odoo, performance analysis of the source code is more important. Database population is one of the methods used to analyze the performance of our code.
Research & Research Methods: Basic Concepts and Types.pptxDr. Sarita Anand
油
This ppt has been made for the students pursuing PG in social science and humanities like M.Ed., M.A. (Education), Ph.D. Scholars. It will be also beneficial for the teachers and other faculty members interested in research and teaching research concepts.
3. Dictionary
It is an unordered collection of items where each
item consist of a key and a value.
It is mutable (can modify its contents ) but Key must be
unique and immutable.
COMPUTERSCIENCE (CLASS XI)
5. Creating A Dictionary
It is enclosed in curly braces {} and each item is separated
from other item by a comma(,)
Within each item, key and value are separated by a colon (:)
Passing value in dictionary at declaration is dictionary
initialization.
get() method is used to access value of a key
E.g.
dict = {Subject': Informatic Practices', 'Class': 11'}
Accessing List Item
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print(dict)
print ("Subject : ", dict['Subject'])
dict.get('Class')
OUTPUT
{'Class': '11', 'Subject': 'Informatics Practices'}
('Subject : ', 'Informatics Practices')
11
Dictionary
6. Iterating / Traversing through A Dictionary
Following example will show how dictionary items can be accessed
through loop.
e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
for i in dict:
print(dict[i])
OUTPUT
Informatics Practices
11
Dictionary
7. Iterating / Traversing through A Dictionary
Following example will show how dictionary items can be accessed
through loop.
e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
for i in dict:
print(dict[i])
OUTPUT
Informatics Practices
11
Updating/Manipulating Dictionary Elements
We can change the individual element of
dictionary.
e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
dict['Subject']='computer science'
print(dict)
OUTPU
T
Dictionary
8. Questions
1. Create dictionary to store 4 student details
with rollno, name, age.
2. Create dictionary for month and no of days
for a year. User is asked to enter month
name and system will show no of days of
that month.
Dictionary
Visit : python.mykvs.in for regular
9. Deleting Dictionary Elements
del, pop() and clear() statement are used to remove
elements from the dictionary.
e.g. DEL
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print('before del', dict)
del dict['Class'] # delete single element
print('after item delete', dict)
del dict #delete whole dictionary
print('after dictionary delete', type(dict))
Output
(before del {'Class': 11, 'Subject': 'Informatics Practices'})
(after item delete {'Subject': 'Informatics Practices'})
('after dictionary delete' <type 'dict'>)
Dictionary
10. pop() method is used to remove a particular item in a
dictionary.
clear() method is used to remove all elements from the dictionary.
e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print('before del', dict)
dict.pop('Class')
print('after item delete', dict)
dict.clear()
print('after clear', dict)
Output
('before del' {'Class': 11, 'Subject': 'Informatics Practices'})
(after item delete {'Subject': 'Informatics Practices'})
('after clear' {})
Dictionary
11. Dictionary
MCQ
Q.1 What will be the output of the following?
d = {abc: 5, def: 6, ghi:7}
print(d1[abc]) # Line 1
print(d[0]) # Line 2
Q.2. Dictionaries are___________ data types of Python.
a) Mutable b)immutable c) simple d) none of these
Q.3. Which of the following can be used to delete item(s) from a
dictionary?
a) Del b) pop() c) popitem() d) all of these
Q.4. Dictionaries are also called_________
a) Mapping b) hashes c) associative arrays
d) all of these
12. Built-in Dictionary Functions
S.No. Function & Description
1 len(dict)----Gives the total length of the dictionary. It is equal to the
number of items in the dictionary.
dict = {'Name': 'Aman', 'Age': 37}
print (len (dict))
OUTPUT ->2
2 str(dict)-----Return a printable stringrepresentationof a Dictionary.
dict = {'Name': 'Aman', 'Age': 37}
>>> "{'Name': 'Aman', 'Age': 37}"
3 type(variable)If variable is dictionary, then it would return a
dictionary type.
dict = {'Name': 'Aman', 'Age': 37}
>>>type(dict)
Dictionary
13. Built-in Dictionary Methods
S.No. Method & Description
1 dict() - creates dictionary # Argument method
x = dict(name = Aman", age = 37, country = India")
Here x is created as dictionary
2
keys() - returns all the available keys
x = dict(name = Aman", age = 37, country = India")
print(x.keys())
OUTPUT->dict_keys(['country', 'age', 'name'])
3
values() - returns all the available values
x = dict(name = Aman", age = 37, country = India")
print(x.values())
OUTPUT->dict_values(['India', 37, 'Aman'])
Dictionary
14. S.No. Method & Description
4
items() - return the list with all dictionary keys with values.
x = dict(name = "Aman", age = 37, country = "India")
print(x.items())
OUTPUT->dict_items([('country', 'India'), ('age', 37), ('name',
'Aman')])
5
update()-used to change the values of a key and add new keys
x = dict(name = "Aman", age = 37, country =
India") d1 = dict(age= 39)
x.update(d1,state="Rajasthan
")
print(x)
OUTPUT-{'country': 'India', 'age': 39,'name':'Aman','state':
'Rajasthan'}
Dictionary
Built-in Dictionary Methods
15. S.No. Method & Description
6
del -used to remove key
x = dict(name = "Aman", age = 37, country = "India")
del x['age']
print(x)
OUTPUT->{'country': 'India', 'name': 'Aman'}
del x -> will remove complete dictionary
7
fromkeys() is used to create dictionary from keys
keys = {'a', 'e', 'i', 'o', 'u' }
value ="Vowel"
vowels = dict.fromkeys(keys, value)
print(vowels)
OUTPUT-> {'i': 'Vowel', 'u': 'Vowel', 'e': 'Vowel', 'a': 'Vowel', 'o': 'Vowel'}
Dictionary
Built-in Dictionary Methods
16. S.No. Method & Description
8 copy() - returns a shallow copy of the dictionary.
x = dict(name = "Aman", age = 37, country = "India")
y=x.copy()
print(y)
print(id(x))
print(id(y))
OUTPUT - >{'country': 'India', 'age': 37, 'name': 'Aman'}
33047872
33047440
9 popitem() removes last item from dictionary
x = dict(name = "Aman", age = 37, country = "India")
x.popitem()
print(x)
OUTPUT-> {'age': 37, 'name': 'Aman'}
Dictionary
Built-in Dictionary Methods
17. S.No. Method & Description
10 setdefault() method returns the value of the item with the specified
key. If the key does not exist, insert the key, with the specified value.
x = dict(name = "Aman", country = "India")
y=x.setdefault('age',39)
print(y)
OUTPUT->
39
11 max() returns key having maximum value
Tv = {'a':100, 'b':1292, 'c' : 88}
Keymax = max(Tv, key=Tv.get)
print(Keymax)
OUTPUT-> b
12 min()- returns key having minimum value
Dict = {'Name': 'Aman', 'Age': 37}
print (min(Dict)
>>> Output - ?
Dictionary
Built-in Dictionary Methods
Dictionary
18. S.No. Method & Description
13 max( )- returns key having maximum value
Dict = {'Name': 'Aman', 'Age': 37}
print (max(Dict)
>>> Output - ?
14. sorted- sort by key or value
dict1 = {'b':100, 'a':12, 'c' : 88}
y = sorted(dict1.items(),key=lambda x:
x[1],reverse=True) print(y)
OUTPUT-> [('b', 100), ('c', 88), ('a',12)]
Dictionary
Built-in Dictionary Methods
19. Competency Based Question
stateCapital = {AndhraPradesh:Hyderabad, Bihar:Patna,
Maharashtra:Mumbai, Rajasthan:Jaipur}
Find output of the following:
1. print(stateCapital.get(Bihar))
2. print(stateCapital.keys()
3. print(stateCapital.values())
4. print(len(stateCapital))
5. del stateCapital [Andhra Pradesh]
print (stateCapital)
6. print(Maharashtra in stateCapital)
Dictionary
Visit : python.mykvs.in for regular
20. 1. create a dictionary with names of
employees, their salary and access them
2. Count the number of times a character
appears in agiven string using a dictionary
Dictionary
Program: