-3
BIG = { "Brand" : ["Clothes" , "Watch"], "Beauty" : ["Skin", "Hair"] }
SMA = { "Clothes" : ["T-shirts", "pants"], "Watch" : ["gold", "metal"],
"Skin" : ["lotion", "base"] , "Hair" : ["shampoo", "rinse"]}

I want to combine this data like this...

BIG = {"Brand" : [ {"Clothes" : ["T-shirts", "pants"]}, {"Watch" : ["gold", "metal"]} ],...

Please tell me how to solve this problem.

Amily
  • 325
  • 1
  • 4
  • 16

2 Answers2

1

First off, those are dictionaries and not lists. Also, I do no know your intention behind merging two dictionaries in that representation.

Anyways, if you want the output to be exactly as you mentioned, then this is the way to do it -

BIG = { "Brand" : ["Clothes" , "Watch"], "Beauty" : ["Skin", "Hair"] }
SMA = { "Clothes" : ["T-shirts", "pants"], "Watch" : ["gold", "metal"],"Skin" : ["lotion", "base"] , "Hair" : ["shampoo", "rinse"]}
for key,values in BIG.items(): #change to BIG.iteritems() in python 2.x
    newValues = []
    for value in values:
        if value in SMA:
            newValues.append({value:SMA[value]})
        else:
            newValues.append(value)
    BIG[key]=newValues

Also, BIG.update(SMA) will not give you the right results in the way you want them to be.

Here is a test run -

>>> BIG.update(SMA)
>>> BIG
{'Watch': ['gold', 'metal'], 'Brand': ['Clothes', 'Watch'], 'Skin': ['lotion', 'base'], 'Beauty': ['Skin', 'Hair'], 'Clothes': ['T-shirts', 'pants'], 'Hair': ['shampoo', 'rinse']}
Gurupad Mamadapur
  • 989
  • 1
  • 13
  • 24
1

Firstly, you need to iterate on first dictionary and search the pair of key in second dictionary.

BIG = { "Brand" : ["Clothes" , "Watch"], "Beauty" : ["Skin", "Hair"] }
SMA = { "Clothes" : ["T-shirts", "pants"], "Watch" : ["gold", "metal"], "Skin" : ["lotion", "base"] , "Hair" : ["shampoo", "rinse"]}

for key_big in BIG:
    for key_sma in BIG[key_big]:
        if key_sma in SMA:
            BIG[key_big][BIG[key_big].index(key_sma)] = {key_sma: SMA.get(key_sma)}

print BIG

The result of code:

>>> {'Brand': [{'Clothes': ['T-shirts', 'pants']}, {'Watch': ['gold', 'metal']}], 'Beauty': [{'Skin': ['lotion', 'base']}, {'Hair': ['shampoo', 'rinse']}]}