def wdba x for k v in db if a k xkv return x Im Trying to

def w(db,a):
x = {}
for k, v in db:
if a == k:
x[k]=[v]
return x


I\'m Trying to check if a key is in a given dictionary, if so, I want to add
that key to another empty dictionary. What am I doing wrong?

Sample Dictionary:

d3 = {\'Me\': [(6,2,2,\'dog\',6,3)] ,\'You\': [(4,5),(8,9)]}

Solution

Here the logic is correct only, but the python has a limitation of unpacking the values in dictionary in the for loop. So instead of unpacking the large array value in for loop, just remove the value part(v) from for loop and get it seperatly from the dictionary. Thus it will looks like:

d3 = {\'Me\': [(6,2,2,\'dog\',6,3)] ,\'You\': [(4,5),(8,9)]}

def w(db,a):
x = {}
for k in db:
if a == k:
x[k]=db[k] #get the value directly from the dictionary db
return x
  
print(w(d3,\'Me\'))

-----------------------------------

OUTPUT:

def w(db,a): x = {} for k, v in db: if a == k: x[k]=[v] return x I\'m Trying to check if a key is in a given dictionary, if so, I want to add that key to anothe

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site