Interview Question: What is the difference between List and Dictionary in Python? 面经:Python 的 List 和 Dictionary 有啥区别?

This is a real interview question: What is the difference between List and Dictionary in Python?
问题: Python 的 List 和 Dictionary 有啥区别?

You need to answer that immediately without googling..
不许查资料,你怎么回答这个面试题?

My answer: a list is like an array whilst a dictionary stores key-value pairs.
我不加思索的回答到: List 就像数组一样 而 Dictionary 是 键值对的一数据结构。

The interviewer asked "is the dictionary ordered"?
面试官继续说,那么 Dictionary 是有序的么?

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.
我还是犹豫了一下,说是无序的,面试官说,为什么?
我说,因为 Python 里的 Dictionary 就如 哈希表一样,而哈希表是没有序的。

He seems satisfied.
面试官似乎很满意。

After I come back, I verified a little bit:
回来之后,我验证了一下。

Create a list (or array)
Python3 创建数组

a=[1,2,3,4,5]

Remove item 3
删掉3

a.remove(3)
print(a) # [1, 2, 4, 5]

Put 3 back to the list
把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.
数组来说, 是有序的,因为每次添加总是在数组的末尾, 我们再来看一下 字典Dictionary

a={1:1,2:2,3:3,4:4,5:5}

Remove key=3
删除3

a.pop(3) # {1: 1, 2: 2, 4: 4, 5: 5}

Put key=3 back to the dictionary
再把3加回到字典中

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}
但是在我朋友的机器上,显示却是 {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])

做了一些顺序有区别的事,那么就很可能会出问题!

Originally published at https://steemit.com Thank you for reading my post, feel free to Follow, Upvote, Reply, ReSteem (repost) @justyy which motivates me to create more quality posts.

原文首发于 https://Steemit.com 首发。感谢阅读,如有可能,欢迎Follow, Upvote, Reply, ReSteem (repost) @justyy 激励我创作更多更好的内容。

// Later, it will be reposted to my blogs: justyy.com, helloacm.com and codingforspeed.com 稍后同步到我的中文博客和英文计算机博客

近期热贴

Recent Popular Posts


Tags: #cn #cn-programming #programming #python #steemstem

H2
H3
H4
3 columns
2 columns
1 column
12 Comments