Python Dictionary Exercises: Practice for Dictionary Manipulation

thumb_up 1  ·  sell Python dictionary exercises, Dictionary manipulation exercises in Python, Dictionary manipulation practice in Python

Example 1

Python program to create a new dictionary by extracting the keys from a given dictionary.

 
d1 = {"one":11, "two":22, "three":33, "four":44, "five":55} keys = ['two', 'five'] d2={} for k in keys: d2[k]=d1[k] print (d2)

It will produce the following output −

{'two': 22, 'five': 55}

Example 2

Python program to convert a dictionary to list of (k,v) tuples.

 
d1 = {"one":11, "two":22, "three":33, "four":44, "five":55} L1 = list(d1.items()) print (L1)

It will produce the following output −

[('one', 11), ('two', 22), ('three', 33), ('four', 44), ('five', 55)]

Example 3

Python program to remove keys with same values in a dictionary.

 
d1 = {"one":"eleven", "2":2, "three":3, "11":"eleven", "four":44, "two":2} vals = list(d1.values())#all values uvals = [v for v in vals if vals.count(v)==1]#unique values d2 = {} for k,v in d1.items(): if v in uvals: d = {k:v} d2.update(d) print ("dict with unique value:",d2)

It will produce the following output −

dict with unique value: {'three': 3, 'four': 44}

Exercise Programs

  • Python program to sort list of dictionaries by values

  • Python program to extract dictionary with each key having non-numeric value from a given dictionary.

  • Python program to build a dictionary from list of two item (k,v) tuples.

  • Python program to merge two dictionary objects, using unpack operator.

 

The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.

Was this answer helpful?

Related Articles

description

Exploring Python's Key Characteristic

Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language. This tutorial will list down some of…

arrow_forward
description

Comparing Python and C++

Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this…

arrow_forward
description

Creating a Python Hello World Program

This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of…

arrow_forward
description

Python's Versatile Application Domains

Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few…

arrow_forward
description

Understanding the Python Interpreter

Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the…

arrow_forward
arrow_back « Back