• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Dictionary / Dictionary Manipulation in Python

Dictionary Manipulation in Python

Author: PFB Staff Writer
Last Updated: August 26, 2020

Overview

A dictionary is a collection of key-value pairs.

A dictionary is a set of key:value pairs.

All keys in a dictionary must be unique.

In a dictionary, a key and its value are separated by a colon.

The key, value pairs are separated with commas.

The key & value pairs are listed between curly brackets ” { } ”

We query the dictionary using square brackets ” [ ] ”

Dictionary Manipulation

Dictionaries are useful whenever you have to items that you wish to link together,
and for example storing results for quick lookup.

Create an empty dictionary

months = {}

Create a dictionary with some pairs

# Note: Each key must be unique

months = { 1 : "January", 
     	2 : "February", 
    	3 : "March", 
        4 : "April", 
     	5 : "May", 
     	6 : "June", 
    	7 : "July",
        8 : "August",
     	9 : "September", 
    	10 : "October", 
        11 : "November",
    	12 : "December" } 

months[1-12] are keys and “January-December” are the values

Print all keys

print "The dictionary contains the following keys: ", months.keys()

Output:

The dictionary contains the following keys: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12]

Accessing

To get a value out of a dictionary, you must supply its key, you cannot provide
the value and get the key

whichMonth = months[1]
print whichMonth

Output: January

To delete an element from a dictionary, use del

del(months[5])
print months.keys()

Output:
[1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12]

To add a new element to a dictionary, assign a value to a new key

months[5] = "May"
print months.keys()

Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

To update an element of a dictionary, assign a new value to its key

months[1] = "Jan"
print months

Output:
{1: ‘Jan’, 2: ‘February’, 3: ‘March’, 4: ‘April’, 5… }

Sorting

sortedkeys = months.keys()
print sortedkeys

Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Dictionaries and Loops

Iterating over keys

for key in months:
    print key, months[key]

Output:
1 January
2 February
3 March
4 April
5 May
6 June
7 July
8 August
9 September
10 October
11 November
12 December

Iterating over (key, value) pairs

for key, value in months.iteritems():
    print key, value

print "The entries in the dictionary are:"
for item in months.keys():
    print "months[ ", item, " ] = ", months[ item ]

Combining List and Dictionary

Example of a list of dictionaries

customers = [{"uid":1,"name":"John"},
    {"uid":2,"name":"Smith"},
           {"uid":3,"name":"Andersson"},
            ]
print customers

Output:
[{‘uid’: 1, ‘name’: ‘John’}, {‘uid’: 2, ‘name’: ‘Smith’}, {‘uid’: 3, ‘name’:
‘Andersson’}]

Print the uid and name of each customer

for x in customer:
    print x["uid"], x["name"]

Output:
1 John
2 Smith
3 Andersson

Modify an entry

This will change the name of customer 2 from Smith to Charlie

customers[2]["name"]="charlie"
print customers

Output:
[{‘uid’: 1, ‘name’: ‘John’}, {‘uid’: 2, ‘name’: ‘Smith’}, {‘uid’: 3, ‘name’:
‘charlie’}]

Add a new field to each entry

for x in customers:
    x["password"]="123456" # any initial value

print customers

Output:
[{‘password’: ‘123456’, ‘uid’: 1, ‘name’: ‘John’}, {‘password’: ‘123456’, ‘uid’:
2, ‘name’: ‘Smith’}, {‘password’: ‘123456’, ‘uid’: 3, ‘name’: ‘Andersson’}]

Delete a field

del customers[1]
print customers

Output:
[{‘uid’: 1, ‘name’: ‘John’}, {‘uid’: 3, ‘name’: ‘Andersson’}]

Delete all fields

# This will delete id field of each entry.
for x in customers:
    del x["id"]

Output:
[{‘name’: ‘John’}, {‘name’: ‘Smith’}, {‘name’: ‘Andersson’}]

For more information about Dictionary, please see this article.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Dictionary, Dictionary Data Structure In Python Author: PFB Staff Writer

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us