Home > front end >  How to add a value to an element in a list which is dictionary?
How to add a value to an element in a list which is dictionary?

Time:11-10

This is my dictionary

d={key1:['value1','value2','value3',...,'valuen'],
   key2:['value1','value2','value3',...,'valuen'],..,
   keyn:['value1','value2','value3',...,'valuen']}

I am trying to add a value to each of the above values to get he below desired dictionary

d={key1:[['value1','matchedvalue1'],['value2','matchedvalue2'],['value3','matchedvalue3'],...,['valuen','matchedvaluen']],
   key2:[['value1','matchedvalue1'],['value2','matchedvalue2'],['value3','matchedvalue3'],...,['valuen','matchedvaluen']],..,
   keyn:[['value1','matchedvalue1'],['value2','matchedvalue2'],['value3','matchedvalue3'],...,['valuen','matchedvaluen']]}

These matchedvalue* are basically retrieved from another dictionary where the value* are keys

so

d2={value1:matchedvalue1,value2:matchedvalue2,value3:matchedvalue3,...,valuen:matchedvaluen}

Now I know how to retrieve the values from this d2 dictioanry, but I am struggling in adding it to the values of the matched key-value-index of dictionary d

for k,v in d.items():
    for i,v in enumerate(d[k]):
            
            d.update(k[i]=d2.get(x))
            ##throws error keyword can't be an expression

            #or tried the below attempt
            #if d2.get(v) is not None:
            #    d[k][i]=d[k][i] ',' d2.get(v)
            #But this doesnt update the values of the key, it returns the same key-values in dictionary d

CodePudding user response:

For the items in the lists - create new lists of pairs:

def pair_items(items, lookup):
    return [[x, lookup.get(x)] for x in items]

By the way, depending on what the items are it's probably more typical in Python to make this a list of tuples instead: [(x, lookup.get(x)) for x in items]

There are then a couple of ways to do this, either create a new data structure without mutating anything:

d3 = {key: pair_items(value, d2) for key, value in d.items()}

Or, mutate everything in-place:

for value in d.values():
    value[:] = pair_items(value, d2)
  • Related