2

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'd like to note that data is a terrible name for a variable since literally everything on a computer is data. :)
1
x = []
for _ in range(len(data)):
    x.append([])

2 Comments

The above script creates empty list like : x=[[], [], [], []].But I want it to be x=[[], [], [], [],[],[],[],[]].Because I am considering the elements of the dictionary inside the dictionary 'data'
He wants to count the sigs, not the Sims/Coms.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.