-1

I've been working on Python for last few months and I encountered this problem. So, I have a dictionary which contains only keys and no values.

{'_id' : None, 'game' : None, 'viewers' : None ....}

And I want to add data which are in the list. For example,

[123456, 'StarCraft 2', 300, ....]

As you might guess, the order of elements inside the list corresponds to the order of keys inside the dict. I think using for loop is the solution but I couldn't come up with a good one.


Extra question: The dict above is now dictionaries inside a list. And, I want to add exactly same dictionary with same keys and new values every time I get a new list of data.

[{'_id': 001, 'game':'StarCraft 2', 'viewers':300, ...}, 
 {'_id': 002, 'game':'Tetiris', 'viewers': 30, ...},
... ]

How do I do that?

Thanks, Python friends!!

mcken
  • 1
  • 2
    You cannot be certain of the order of the keys in the dict. Thus, this is, at best, fragile, at worst plain wrong. – JohanL Aug 18 '17 at 12:01
  • Further, how come you have a list of data to begin with. That sounds odd. – JohanL Aug 18 '17 at 12:02

1 Answers1

1

Actually you cannot do that with a dict because the order is not conserved. But you can use the class OrderedDict as shown here: Python dictionary, how to keep keys/values in same order as declared?

What you could do is have a list with your keys to keep track of the order:

my_keys = ['_id', 'game', 'viewers']
for index, elt in enumerate(my_data):
     my_dict[my_keys[index]] = elt
Coding thermodynamist
  • 1,340
  • 1
  • 10
  • 18
  • 1
    "because the order is not conserved". Now it is, but only as a side effect. https://stackoverflow.com/questions/39980323/dictionaries-are-ordered-in-python-3-6 – damisan Aug 18 '17 at 12:07
  • True, since 3.6 it is conserved but it might not stay that way: https://docs.python.org/3/whatsnew/3.6.html – Coding thermodynamist Aug 18 '17 at 12:08