'How can I create an imbricated dictionnary from another dictionnary that has different numbers of element for each key combined with a function
I have a problem for inialize an imbricated dictionnary from another one that has different numbers of element for each key.
So basically my first dictionnary is like : {0: [238, 159], ..., 7 [290, 311, 8], 67 [135, 173, 69, 68, 70, 71], ...} it shows where you can go from the key you're choosing, for example from the key 0 you can go to points 238 and 159. And I have a funtion Time that returns me how much time it takes to go from a point to another one.
The result I want is like: {0: {238: Time(0, 238), 159: Time(0, 159)}, ..., {7: {290: Time(7, 290), 311: Time(7 ,311), 8: Time(7, 8)}, ...}
As I said all key (0-375) from the 1st dictionnary has between 1-6 elements in their list. And I took all the data from a .txt
*Sorry for my english, don't hesitate to ask me questions if you don't understand, also I can show you my code but its kinda long to understand so I tried to simplify
Solution 1:[1]
I have made a sample Time class you can replace it with yours. newDict will be the dictionary in the form that you are looking for.
class Time:
def __init__(self,x,y):
self.x = x
self.y = y
def printXY(self):
return ("Time (" + str(self.x) + "," + str(self.y) + ")")
def solution():
dict = {0:[238,159],
7:[290,311,8],
67:[135, 173, 69, 68, 70, 71]}
newDict = {}
for key, value in dict.items():
tempDict = {}
for v in value:
tempDict[v] = Time(key,v)
newDict[key] = tempDict
for key,value in newDict.items():
print("For key = " + str(key))
for k,v in value.items():
print(str(k) + ":"+ v.printXY())
print ("")
'''
OUTPUT:
For key = 0
238:Time (0,238)
159:Time (0,159)
For key = 7
290:Time (7,290)
311:Time (7,311)
8:Time (7,8)
For key = 67
135:Time (67,135)
173:Time (67,173)
69:Time (67,69)
68:Time (67,68)
70:Time (67,70)
71:Time (67,71)
'''
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Swapnil Chauhan |
