As it has been said, dict
s do not guanrantee any kind of order by keys (they may be ordered by insert time depending on what python version you use).
But you can always represent a dict as a list of key-value tuples:
d1 = {'id': '1234', 'Name': 'John', 'dob': '01/01/2001', 'Address': 'Long Street'}
d2 = {'id': '1235', 'dob': '01/01/2002', 'Address': 'Tower Street', 'Name': 'Michael'}
print(sorted(d1.items())) # [('Address', 'Long Street'), ('Name', 'John'), ('dob', '01/01/2001'), ('id', '1234')]
print(sorted(d2.items())) # [('Address', 'Tower Street'), ('Name', 'Michael'), ('dob', '01/01/2002'), ('id', '1235')]
You mentioned in a comment that the order was needed to write to a CSV file. In that case, forget about the order. csv.DictWritter
allows to write to a CSV file by providing dicts and it will order them according to the columns.
import csv
d1 = {'id': '1234', 'Name': 'John', 'dob': '01/01/2001', 'Address': 'Long Street'}
d2 = {'id': '1235', 'dob': '01/01/2002', 'Address': 'Tower Street', 'Name': 'Michael'}
with open('OUTPUT_FILE.csv', 'w', newline='') as f:
fieldnames = 'id', 'Name', 'dob', 'Address'
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader() # id,Name,dob,Address
writer.writerow(d1) # 1234,John,01/01/2001,Long Street
writer.writerow(d2) # 1235,Michael,01/01/2002,Tower Street