BIG = { "Brand" : ["Clothes" , "Watch"], "Beauty" : ["Skin", "Hair"] }
SMA = { "Clothes" : ["T-shirts", "pants"], "Watch" : ["gold", "metal"],
"Skin" : ["lotion", "base"] , "Hair" : ["shampoo", "rinse"]}
我想要合并这些数据 像这样...
BIG = {"Brand" : [ {"Clothes" : ["T-shirts", "pants"]}, {"Watch" : ["gold", "metal"]} ],...
请告诉我如何解决这个问题。
答案 0 :(得分:1)
首先,这些是字典而不是列表。另外,我不知道你在合并两个词典背后的意图。
无论如何,如果你想让输出完全按照你提到的那样,那就是这样做的方法 -
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
此外,BIG.update(SMA)
不会按照您希望的方式为您提供正确的结果。
这是一个测试运行 -
>>> BIG.update(SMA)
>>> BIG
{'Watch': ['gold', 'metal'], 'Brand': ['Clothes', 'Watch'], 'Skin': ['lotion', 'base'], 'Beauty': ['Skin', 'Hair'], 'Clothes': ['T-shirts', 'pants'], 'Hair': ['shampoo', 'rinse']}
答案 1 :(得分:0)
首先,您需要迭代第一个字典并在第二个字典中搜索该对密钥。
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
代码的结果:
>>> {'Brand': [{'Clothes': ['T-shirts', 'pants']}, {'Watch': ['gold', 'metal']}], 'Beauty': [{'Skin': ['lotion', 'base']}, {'Hair': ['shampoo', 'rinse']}]}