complete the list programming assignment . complete the dictionary programming assignment.
HTML and CSS
Learn HTML Learn CSS Learn Bootstrap Learn W3.CSS Learn Colors Learn Icons Learn Graphics Learn SVG Learn Canvas Learn How To Learn SassXML
Learn XML Learn XML AJAX Learn XML DOM Learn XML DTD Learn XML Schema Learn XSLT Learn XPath Learn XQueryJavaScript
Learn JavaScript Learn jQuery Learn React Learn AngularJS Learn JSON Learn AJAX Learn W3.JSProgramming
Learn Python Learn Java Learn C++Server Side
Learn SQL Learn PHP Learn ASP Learn Node.js Learn Raspberry PiWeb Building
Web Templates Web Statistics Web Certificates Web Editor Web DevelopmentXML
Learn XML Learn XML AJAX Learn XML DOM Learn XML DTD Learn XML Schema Learn XSLT Learn XPath Learn XQuery ×HTML
HTML Tag Reference HTML Event Reference HTML Color Reference HTML Attribute Reference HTML Canvas Reference HTML SVG Reference HTML Character Sets Google Maps ReferenceCSS
CSS Reference CSS Browser Support CSS Selector Reference Bootstrap 3 Reference Bootstrap 4 Reference W3.CSS Reference Icon Reference Sass ReferenceJavaScript
JavaScript Reference HTML DOM Reference jQuery Reference AngularJS Reference W3.JS ReferenceProgramming
Python Reference Java ReferenceServer Side
SQL Reference PHP Reference ASP ReferenceXML
XML Reference XML Http Reference XSLT Reference XML Schema ReferenceCharacter Sets
HTML Character Sets HTML ASCII HTML ANSI HTML Windows-1252 HTML ISO-8859-1 HTML Symbols HTML UTF-8 ×Exercises
HTML Exercises CSS Exercises JavaScript Exercises SQL Exercises PHP Exercises Python Exercises jQuery Exercises Bootstrap Exercises Java Exercises C++ ExercisesQuizzes
HTML Quiz CSS Quiz JavaScript Quiz SQL Quiz PHP Quiz Python Quiz jQuery Quiz Bootstrap Quiz XML QuizCertificates
HTML Certificate CSS Certificate JavaScript Certificate SQL Certificate PHP Certificate Python Certificate jQuery Certificate Bootstrap Certificate XML CertificatePython Tutorial
Python HOME Python Intro Python Get Started Python Syntax Python Comments Python Variables Python Data Types Python Numbers Python Casting Python Strings Python Booleans Python Operators Python Lists Python Tuples Python Sets Python Dictionaries Python If...Else Python While Loops Python For Loops Python Functions Python Lambda Python Arrays Python Classes/Objects Python Inheritance Python Iterators Python Scope Python Modules Python Dates Python JSON Python RegEx Python PIP Python Try...Except Python Command Input Python String FormattingFile Handling
Python File Handling Python Read Files Python Write/Create Files Python Delete FilesPython MySQL
MySQL Get Started MySQL Create Database MySQL Create Table MySQL Insert MySQL Select MySQL Where MySQL Order By MySQL Delete MySQL Drop Table MySQL Update MySQL Limit MySQL JoinPython MongoDB
MongoDB Get Started MongoDB Create Database MongoDB Create Collection MongoDB Insert MongoDB Find MongoDB Query MongoDB Sort MongoDB Delete MongoDB Drop Collection MongoDB Update MongoDB LimitPython Reference
Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python KeywordsModule Reference
Random Module Requests ModulePython How To
Remove List Duplicates Reverse a StringPython Examples
Python Examples Python Exercises Python Quiz Python CertificatePython Dictionaries
❮ Previous Next ❯Dictionary
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.
Example
Create and print a dictionary:
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict) Run example »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"] Run example »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") Run example »Change Values
You can change the value of a specific item by referring to its key name:
Example
Change the "year" to 2018:
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["year"] = 2018 Run example »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) Run example »Example
Print all values in the dictionary, one by one:
for x in thisdict: print(thisdict[x]) Run example »Example
You can also use the values() function to return values of a dictionary:
for x in thisdict.values(): print(x) Run example »Example
Loop through both keys and values, by using the items() function:
for x, y in thisdict.items(): print(x, y) Run example »Check if Key Exists
To determine if a specified key is present in a dictionary use the in keyword:
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") Run example »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)) Run example »Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Example
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["color"] = "red" print(thisdict) Run example »Removing Items
There are several methods to remove items from a dictionary:
Example
The pop() method removes the item with the specified key name:
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.pop("model") print(thisdict) Run example »Example
The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.popitem() print(thisdict) Run example »Example
The del keyword removes the item with the specified key name:
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } del thisdict["model"] print(thisdict) Run example »Example
The del keyword can also delete the dictionary completely:
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } del thisdict print(thisdict) #this will cause an error because "thisdict" no longer exists. Run example »Example
The clear() keyword empties the dictionary:
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.clear() print(thisdict) Run example »Copy 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) Run example »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) Run example »Nested Dictionaries
A dictionary can also contain many dictionaries, this is called nested dictionaries.
Example
Create a dictionary that contain three dictionaries:
myfamily = { "child1" : { "name" : "Emil", "year" : 2004 }, "child2" : { "name" : "Tobias", "year" : 2007 }, "child3" : { "name" : "Linus", "year" : 2011 } } Run example »Or, if you want to nest three dictionaries that already exists as dictionaries:
Example
Create three dictionaries, than create one dictionary that will contain the other three dictionaries:
child1 = { "name" : "Emil", "year" : 2004 } child2 = { "name" : "Tobias", "year" : 2007 } child3 = { "name" : "Linus", "year" : 2011 } myfamily = { "child1" : child1, "child2" : child2, "child3" : child3 } Run example »The dict() Constructor
It is also possible to use the dict() constructor to make a new dictionary:
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) Run example »Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.
| Method | Description |
|---|---|
| clear() | Removes all the elements from the dictionary |
| copy() | Returns a copy of the dictionary |
| fromkeys() | Returns a dictionary with the specified keys and values |
| get() | Returns the value of the specified key |
| items() | Returns a list containing the a tuple for each key value pair |
| keys() | Returns a list containing the dictionary's keys |
| pop() | Removes the element with the specified key |
| popitem() | Removes the last inserted key-value pair |
| setdefault() | Returns the value of the specified key. If the key does not exist: insert the key, with the specified value |
| update() | Updates the dictionary with the specified key-value pairs |
| values() | Returns a list of all the values in the dictionary |
Test Yourself With Exercises
Exercise:
Use the get method to print the value of the "model" key of the car dictionary.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print()
Submit Answer »
❮ Previous
Next ❯
COLOR PICKER
HOW TO
Tabs Dropdowns Accordions Side Navigation Top Navigation Modal Boxes Progress Bars Parallax Login Form HTML Includes Google Maps Range Sliders Tooltips Slideshow Filter List Sort ListSHARE
CERTIFICATES
HTML CSS JavaScript SQL Python PHP jQuery Bootstrap XML
Read More » REPORT ERROR PRINT PAGE FORUM ABOUT ×Your Suggestion:
Your E-mail: Page address: Description: Submit ×Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial jQuery Tutorial Java Tutorial C++ TutorialTop References
HTML Reference CSS Reference JavaScript Reference SQL Reference Python Reference W3.CSS Reference Bootstrap Reference PHP Reference HTML Colors jQuery Reference Java Reference Angular ReferenceTop Examples
HTML Examples CSS Examples JavaScript Examples How To Examples SQL Examples Python Examples W3.CSS Examples Bootstrap Examples PHP Examples jQuery Examples Java Examples XML ExamplesWeb Certificates
HTML Certificate CSS Certificate JavaScript Certificate SQL Certificate Python Certificate jQuery Certificate PHP Certificate Bootstrap Certificate XML Certificate Get Certified » W3Schools is optimized for learning, testing, and training. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy. Copyright 1999-2019 by Refsnes Data. All Rights Reserved. Powered by W3.CSS.