- Hands-On Data Science and Python Machine Learning
- Frank Kane
- 327字
- 2021-07-15 17:15:02
Dictionaries
Finally, the last data structure that we'll see a lot in Python is a dictionary, and you can think of that as a map or a hash table in other languages. It's a way to basically have a sort of mini-database, sort of a key/value data store that's built into Python. So let's say, I want to build up a little dictionary of Star Trek ships and their captains:

I can set up a captains = {}, where curly brackets indicates an empty dictionary. Now I can use this sort of a syntax to assign entries in my dictionary, so I can say captains for Enterprise is Kirk, for Enterprise D it is Picard, for Deep Space Nine it is Sisko, and for Voyager it is Janeway. Now I have, basically, this lookup table that will associate ship names with their captain, and I can say, for example, print captains["Voyager"], and I get back Janeway.
A very useful tool for basically doing lookups of some sort. Let's say you have some sort of an identifier in a dataset that maps to some human-readable name. You'll probably be using a dictionary to actually do that look up when you're printing it out.
We can also see what happens if you try to look up something that doesn't exist. Well, we can use the get function on a dictionary to safely return an entry. So in this case, Enterprise does have an entry in my dictionary, it just gives me back Kirk, but if I call the NX-01 ship on the dictionary, I never defined the captain of that, so it comes back with a None value in this example, which is better than throwing an exception, but you do need to be aware that this is a possibility:
print (captains.get("NX-01"))
The output of the above code is as follows:
None
The captain is Jonathan Archer, but you know, I'm get a little bit too geeky here now.
- C++程序設計教程
- 深入核心的敏捷開發:ThoughtWorks五大關鍵實踐
- 密碼學原理與Java實現
- SQL Server 2016從入門到精通(視頻教學超值版)
- Web交互界面設計與制作(微課版)
- Mastering C# Concurrency
- Learning Laravel 4 Application Development
- Python完全自學教程
- Visual Studio 2015高級編程(第6版)
- 深入剖析Java虛擬機:源碼剖析與實例詳解(基礎卷)
- 軟件工程基礎與實訓教程
- Python期貨量化交易實戰
- scikit-learn Cookbook(Second Edition)
- VMware vSphere 5.5 Cookbook
- 基于JavaScript的WebGIS開發