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

ich diese Daten kombinieren möchten so ...wie verschiedene komplexe Liste kombinieren mit Python

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

Bitte sagen Sie mir, wie dieses Problem zu lösen.

+4

Mögliche Duplikat (http://stackoverflow.com/questions/38987/how-to -merge-two-python-dictionaries-in-single-expression) –

+0

'BIG.update (SMA)' –

Antwort

1

Zunächst sind das Wörterbücher und keine Listen. Außerdem kenne ich Ihre Absicht nicht, zwei Wörterbücher in dieser Darstellung zusammenzuführen.

Auch immer, wenn Sie die Ausgabe wollen genau zu sein, wie Sie erwähnt haben, dann ist dies der Weg, es zu tun -

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 

Auch BIG.update(SMA) werden Sie nicht die richtigen Ergebnisse geben in der Art und Weise Sie wollen, sein.

Hier ist ein Testlauf -

>>> BIG.update(SMA) 
>>> BIG 
{'Watch': ['gold', 'metal'], 'Brand': ['Clothes', 'Watch'], 'Skin': ['lotion', 'base'], 'Beauty': ['Skin', 'Hair'], 'Clothes': ['T-shirts', 'pants'], 'Hair': ['shampoo', 'rinse']} 
0

Zum einen müssen Sie auf erste Wörterbuch iterieren und das Paar Schlüssel in der zweiten Wörterbuch suchen.

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 

Das Ergebnis Code: [? Wie zwei Python Wörterbücher in einem einzigen Ausdruck verschmelzen]

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