Reputation: 763
I have a array of strings like this:
Array = ['ABC', 'DEF', 'GHI']
How do I map this into a dictionary of dictionaries having the following shape?
dictionary = {
'ABC': {'DEF': auxFunction(ABC,DEF), 'GHI': auxFunction(ABC,GHI)},
'DEF': {'ABC': auxFunction(DEF,ABC), 'GHI': auxFunction(DEF,GHI)},
'GHI': {'ABC': auxFunction(GHI,ABC), 'DEF': auxFunction(GHI,DEF)},
}
Upvotes: 3
Views: 111
Reputation: 50864
You can do it with two dict comprehensions
dictionary = {name: {x: auxFunction(name, x) for x in array if x != name} for name in array}
{'ABC': {'DEF': auxFunction(ABC, DEF), 'GHI': auxFunction(ABC, GHI)},
'DEF': {'ABC': auxFunction(DEF, ABC), 'GHI': auxFunction(DEF, GHI)},
'GHI': {'ABC': auxFunction(GHI, ABC), 'DEF': auxFunction(GHI, DEF)}}
Upvotes: 4
Reputation: 1148
>>> auxFunction = max
>>> {Array[i]: {Array[j]: auxFunction(Array[i], Array[j]) for j in range(len(Array)) if j != i} for i in range(len(Array))}
{456: {123: 456, 789: 789}, 123: {456: 456, 789: 789}, 789: {456: 789, 123: 789}}
Upvotes: 1
Reputation: 2076
You Can Try this:
finalDict= {}
Array = ['ABC', 'DEF', 'GHI']
for i in Array:
tempDict = {}
for j in Array:
if i!= j:
tempDict[j] = "A calculation between " + i + " - " + j
finalDict[i] = tempDict
print(finalDict)
Output:
{
'ABC': {'DEF': 'A calculation between ABC - DEF', 'GHI': 'A calculation between ABC - GHI'},
'DEF': {'ABC': 'A calculation between DEF - ABC', 'GHI': 'A calculation between DEF - GHI'},
'GHI': {'ABC': 'A calculation between GHI - ABC', 'DEF': 'A calculation between GHI - DEF'}
}
Upvotes: 3