0% found this document useful (0 votes)
26 views2 pages

Dictionary

dictionary solution
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views2 pages

Dictionary

dictionary solution
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Grade 11- Computer Science

Solution from Suimta Arora

#1 Given the dictionary x = ['kl': 'vl', 'k2': 'v2', 'k3': 'v3'), create a dictionary with the opposite mapping,
i.e., write a program to create the dictionary as: inverted_x = {'v1': 'k1', 'v2': 'k2', 'v3': 'k3'}

#Invert the dictionary mapping.

x = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}

inverted_x = {v: k for k, v in x.items()}

print(inverted_x)

Output:

{'v1': 'k1', 'v2': 'k2', 'v3': 'k3'}

#2. Given two dictionaries say D1 and D2. Write a program that lists the overlapping keys of the two
dictionaries, ie., if a key of D1 is also a key of D2, the list it.

#List overlapping keys between two dictionaries.

D1 = {'a': 1, 'b': 2, 'c': 3}

D2 = {'b': 4, 'c': 5, 'd': 6}

overlapping_keys = [key for key in D1 if key in D2]

print(overlapping_keys)

Output:

['b', 'c']

#3. Write a program that checks if two same values in a dictionary have different keys. That is, for
dictionary D1 = { 'a': 10, 'b': 20, 'c': 10), the program should print "2 keys have same values" and for
dictionary D2 = { 'a': 10, 'b': 20, 'c': 30}, the program should print "No keys have same values".

#Check if two keys have the same values.

D1 = {'a': 10, 'b': 20, 'c': 10}

values = list(D1.values())

if len(values) != len(set(values)):

print("2 keys have same values")

1
Grade 11- Computer Science
else:

print("No keys have same values")

Output:

2 keys have same values

#4. A dictionary D1 has values in the form of lists of numbers. Write a program to create a new
dictionary D2 having same keys as D1 but values as the sum of the list elements e.g., D1 = {'A': [1, 2,
3], 'B' : [4, 5, 6]} D2 is {'A': 6, 'B' : 15} then D2 is {‘A’:6,’B’:15}

#Sum list elements in dictionary values and create a new dictionary.

D1 = {'A': [1, 2, 3], 'B': [4, 5, 6]}

D2 = {key: sum(value) for key, value in D1.items()}

print(D2)

Output:

{'A': 6, 'B': 15}

#5. Write a program to check if a dictionary is contained in another dictionary e.g., if d1= {1:11, 2:12}
d2 = {1:11, 2:12, 3:13, 4:15} then d1 is contained in d2.

#Check if one dictionary is contained in another.

d1 = {1: 11, 2: 12}

d2 = {1: 11, 2: 12, 3: 13, 4: 15}

is_contained = all(key in d2 and d1[key] == d2[key] for key in d1)

print("d1 is contained in d2" if is_contained else "d1 is not contained in d2")

Output:

d1 is contained in d2

You might also like