0

I'm wondering why a dictionary built by function is in wrong order. It starts from location of the user, not from his first and last name. It is a code from "Python Crash Course" (chapter 8) but SUblime Text prints it like I described. Could some good spirit help me. I'm new in this area.

def build_profile(first, last, **user_info):
    """Builds dictionary with user information"""
    user_info['first_name'] = first
    user_info['last_name'] = last
    return user_info
user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)

Result:

{'location': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'}

zagrab
  • 1
  • 1
    Dictionaries do not have such a thing as order at all. They are innately, by definition, unordered. – Charles Duffy May 10 '21 at 17:37
  • If you want the values in a specific order, you shouldn't be using `dict`. – Silvio Mayolo May 10 '21 at 17:38
  • Checkout OrderedDict if you want ordering – pcauthorn May 10 '21 at 17:39
  • _nod_ -- the linked duplicate discusses `OrderedDict`s. – Charles Duffy May 10 '21 at 17:40
  • 3
    It's worth pointing out that in Python 3.6 and up, dictionaries are in fact insertion ordered. https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6 . Location and field are being inserted to the `user_info` dict first when it is created with the double star, and so the order is preserved. (This assumes you're running on Python 3.6 or up, which isn't specified.) – Forensic_07 May 10 '21 at 17:54
  • @Forensic_07 The C-implementation of Python 3.6 (CPython 3.6) is insertion ordered as an implementation detail. Other implementations may vary. Python 3.7 actually specifies it. – Mark Tolonen May 10 '21 at 18:20

0 Answers0