2
a_lst = list()
b_lst = list()
tmp = list()
c_dct = dict()
while True:
   a = raw_input("a=")
   a_lst.append(a)
   b = raw_input("b=")
   b_lst.append(b)
   if a == "end":
      break
a_lst.remove('end')
print a_lst
print b_lst


for i in range(len(a_lst)):
   c_dct[a_lst[i]] = b_lst[i] 


print c_dct

In this code, I combine 2 lists to create the dictionary. In the result, the dictionary is not the same position as the input. For example,

c_dct = {'q': 'w', 'e': 'r', 'o': 'p', '1': '2', '3': '4', '5': '6', 't': 'y', '7': '8', '9': '0', 'u': 'i'}

instead of

c_dct =  {'1': '2', '3': '4', '5': '6','7': '8', '9': '0','q': 'w', 'e': 'r','t': 'y','u': 'i','o': 'p'}

What is going on the code? How to slove this problem? Thank You very much!

1
  • Why don't you check if a == "end" before adding it to the list (or before asking for another b value, for that matter)? Commented Mar 17, 2016 at 12:32

2 Answers 2

6

Dictionaries do not maintain order by default. If you need an ordered dictionary, you can use the following:

from collections import OrderedDict

Take a look at the documentation

Sign up to request clarification or add additional context in comments.

Comments

5

Dictionaries are unordered by design. So, everything is OK and you can't create a perfectly ordered dictionary.

Here is a quote from the Python documentation (section 5.5):

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.