0

This is baffling me:

row = {'Item1':1, 'Item2':2, 'Item3':3}

fieldnames = list(row.keys())
print(list(row))

fieldnames.append('Item4')          
print(list(row))

Outputs

['Item3', 'Item1', 'Item2']
['Item3', 'Item1', 'Item2']

When run again:

['Item3', 'Item2', 'Item1']
['Item3', 'Item2', 'Item1']

What? Does keys() access the list randomly? Any better way of doing what I want? (i.e get the keys of a dict in the order they appear)

toonarmycaptain
  • 2,093
  • 2
  • 18
  • 29
willwade
  • 1,998
  • 2
  • 16
  • 22

1 Answers1

-1

As per the Python documentation:

The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it).

https://docs.python.org/2/tutorial/datastructures.html