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:
1 | a=[1,2,3,4,5] |
a=[1,2,3,4,5]
Remove item 3:
1 2 | a.remove(3) print(a) # [1, 2, 4, 5] |
a.remove(3) print(a) # [1, 2, 4, 5]
Put 3 back to the list:
1 2 | a.append(3) print(a) # [1, 2, 4, 5, 3] |
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.
1 | a={1:1,2:2,3:3,4:4,5:5} |
a={1:1,2:2,3:3,4:4,5:5}
Remove key=3:
1 | a.pop(3) # {1: 1, 2: 2, 4: 4, 5: 5} |
a.pop(3) # {1: 1, 2: 2, 4: 4, 5: 5}
Put key=3 back to the dictionary.
1 | a[3] = 3 |
a[3] = 3
and we’ve got the original dictionary.
1 | print(a) # a={1:1,2:2,3:3,4:4,5:5} |
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!
1 2 | for key in a: do_something_with_order_matters(a[key]) |
for key in a: do_something_with_order_matters(a[key])
You may also like: 面经:Python 的 List 和 Dictionary 有啥区别?
–EOF (The Ultimate Computing & Technology Blog) —
loading...
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
Hi There ,
Great info! I recently came across your blog and have been reading along.
I thought I would leave my first comment. I don’t know what to say except that I have
I have a basic image, in color.
I would like to change every color by another color.
I know the functions putpixel, et caetera.
My problem, it is that I do not know how to separate, to indicate every “zone” of color.
For example: transform all the green pixels into another color, all the red in an other one, et caetera.
Anybody would have an edvice to give me?
I look forward to see your next updates.
Ciao,
Irene Hynes