+ 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]
5 Réponses
+ 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.
+ 1
Show us your attempt, please.
+ 1
Thanks a ton
+ 1
https://code.sololearn.com/ckNondB1JT7f/?ref=app
To learn more about how to work with dicts...
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:
[ ]