I have a dictionary like this:
data = {
'Sim_1':{
'sig1':[
1,
2,
3
],
'sig2':[
4,
5,
6
]
},
'Sim_2':{
'sig3':[
7,
8,
9
],
'sig4':[
10,
11,
12
]
},
'Com_1':{
'sig5':[
13,
14,
15
],
'sig6':[
16,
17,
18
]
},
'Com_2':{
'sig7':[
19,
20,
21
],
'sig8':[
128,
23,
24
]
}
}
I want to create a list variable like this:
x=[[],[],[],[],[],[],[],[]]
Basically I want to create a list of empty lists whose length is equal to the number of keys in the dictionary which I have mentioned above. Here the thing is the dictionary may vary. That is the number of signals in each dictionary inside the dictionary 'data' can vary.
x = []
for _ in range(len(data)):
x.append([])
List comprehensions are great for moving through multidimensional data structures like this.
In this case it's a two-tiered data structure so you need two inner for
loops.
>>> [[] for simcom in data.values() for sig in simcom ]
[[], [], [], [], [], [], [], []]
It's really nice because if you keep them simple you can read them off like an English phrase. The above says
An empty list for each sim/com which is a value in my data dict, for each signal within this sim/com.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.