create 2 dictionaries and a list of thier overlapping keys | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

create 2 dictionaries and a list of thier overlapping keys

Create 2 dictionaries D1 and D2 and create a list of the overlapping keys(i.e a list of the keys that exist in both D1 and D2 Eg: D1={1:'a',2:'b',3:'c',4:'d'} D2={5:'d',3:'f',7:'b',2:'a',1:'y'} Output: L1=[3,2,1]

22nd Dec 2019, 10:06 AM
cherry
cherry - avatar
5 Answers
+ 1
You can easily iterate on all keys of a dictionary. D3 = list() for key1 in D1: for key2 in D2: if key1 == key2: D3.append(key1) Explanation : You create an empty list D3 that will hold all same keys. Then, you iterate on D1 (for each key1 in the dictionary D1) and on D2 (for each key2 in the dictionary D2) and compare key1 and key2. If they are the same, simply add them to D3.
22nd Dec 2019, 10:24 AM
Théophile
Théophile - avatar
+ 1
Show us your attempt, please.
22nd Dec 2019, 10:13 AM
Théophile
Théophile - avatar
+ 1
Thanks a ton
22nd Dec 2019, 10:26 AM
cherry
cherry - avatar
+ 1
https://code.sololearn.com/ckNondB1JT7f/?ref=app To learn more about how to work with dicts...
22nd Dec 2019, 10:28 AM
Théophile
Théophile - avatar
0
D1={1:'a',2:'b',3:'c',4:'d'} D2={5:'d',3:'f',7:'b',2:'a',1:'y'} D3=dict() a=d1.keys() b=d2.keys() if a==b : d3[a]=b print(list(d3)) The output that this code gives is: [ ]
22nd Dec 2019, 10:20 AM
cherry
cherry - avatar