when i used a function it messed up the sequence of my dictionary
arr = ['loyd1', 'loyd2', 'loyd3', 'loyd4'] list = {k: 0 for k in arr} {'loyd1': 0, 'loyd3': 0, 'loyd2': 0, 'loyd4': 0}
Asked
Active
Viewed 50 times
0

Aran-Fey
- 39,665
- 11
- 104
- 149

Saitama Kalbo
- 29
- 7
-
6Possible duplicate of [Dictionaries: How to keep keys/values in same order as declared?](https://stackoverflow.com/questions/1867861/dictionaries-how-to-keep-keys-values-in-same-order-as-declared) – Aran-Fey Jun 25 '18 at 12:39
-
Use ordereddict from collections – machnine Jun 25 '18 at 12:45
3 Answers
0
You can use OrderedDict()
to keep the same order in which the dictionary was created.
from collections import OrderedDict
arr = ['loyd1', 'loyd2', 'loyd3', 'loyd4']
dico = OrderedDict((k, 0) for k in arr)

Divadrare
- 26
- 2
0
please use OrderDict!
from collections import OrderDict
arr = ['loyd1', 'loyd2', 'loyd3', 'loyd4']
res = OrderedDict()
res = {i: 0 for i in arr}
print(res)

jian0lu
- 1
- 2
-1
If you do not want to import any module, simply do this:
arr = ['loyd1', 'loyd2', 'loyd3', 'loyd4']
dict={}
for k in arr:
dict[k]=0

Thomas Ayoub
- 29,063
- 15
- 95
- 142

MOHIT SHARMA
- 1
- 1
-
That is no different from a dict comprehension, except for the fact that it's more verbose. – Aran-Fey Jun 25 '18 at 14:41