A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/python/python_dictionary_exercises.htm below:

Python - Dictionary Exercises

Python - Dictionary Exercises Dictionary Exercise 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}
Dictionary Exercise 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)]
Dictionary Exercise 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}
Dictionary Exercise Programs

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4