This is a real interview question: What is the difference between List and Dictionary in Python?
You need to answer that immediately without googling..
My answer: a list is like an array whilst a dictionary stores key-value pairs.
The interviewer asked “is the dictionary ordered”?
What? I think he meant, can we trust the sequence when iterating the dictionary?
With some doubt, I still said: it is unordered.. because the dictionary in Python is like hash table and a hash table is clearly unordered.
He seems satisfied.
After I come back, I verified a little bit about this, first I created a list (or array) in Python3:
a=[1,2,3,4,5]
Remove item 3:
a.remove(3)
print(a) # [1, 2, 4, 5]
Put 3 back to the list:
a.append(3)
print(a) # [1, 2, 4, 5, 3]
So, yes, the list is ‘ordered’ because the new item always is appended to the end of the list. Let’s take a look at the dictionary.
a={1:1,2:2,3:3,4:4,5:5}
Remove key=3:
a.pop(3) # {1: 1, 2: 2, 4: 4, 5: 5}
Put key=3 back to the dictionary.
a[3] = 3
and we’ve got the original dictionary.
print(a) # a={1:1,2:2,3:3,4:4,5:5}
However, it is inconsistent on my friend’s PC, which shows {1:1,2:2,4:4,5:5,3:3}. So, the order cannot be trusted when you iterate the dictionary. The following code might break!
for key in a:
do_something_with_order_matters(a[key])
You may also like: 面经:Python 的 List 和 Dictionary 有啥区别?
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: How to Set Voting Weight (using Python Script) for Minnows with Less than 500 Steem Power on Steemit?
Next Post: A Good-Content-Upvote SteemIt Bot for CN Community
