- Python Data Structures and Algorithms
- Benjamin Baka
- 407字
- 2021-07-09 19:45:02
Dictionaries
Dictionaries are arbitrary collections of objects indexed by numbers, strings, or other immutable objects. Dictionaries themselves are mutable; however, their index keys must be immutable. The following table contains all the dictionary methods and their descriptions:

Python dictionaries are the only built-in mapping type and they are similar to hash tables or associative arrays found in other languages. They can be thought of as a mapping from a set of keys to a set of values. They are created using the syntax {key:value}. For example, the following creates a dictionary mapping words to numerals:
d ={'one': 1 , 'two': 2, 'three': 3 } # creates a dictionary
We can add keys and values as follows:
d['four']=4 #add an item
Or update multiple values using the following:
d.update({'five': 5, 'six': 6}) #add multiple items
When we inspect d, we get the following:

We can test for the occurrence of a value using the in operator, for example:

It should be noted that the in operator, when applied to dictionaries, works in a slightly different way to when it is applied to a list. When we use the in operator on a list, the relationship between the time it takes to find an element and the size of the list is considered linear. That is, as the size of the list gets bigger, the corresponding time it takes to find an element grows, at most, linearly. The relationship between the time an algorithm takes to run compared to the size of its input is often referred to as its time complexity. We will talk more about this important topic in the next (and subsequent) chapters.
In contrast to the list object, when the in operator is applied to dictionaries, it uses a hashing algorithm and this has the effect of the increase in time for each lookup almost independent of the size of the dictionary. This makes dictionaries extremely useful as a way to work with large amounts of indexed data. We will talk more about this important topic of rates of growth hashing in Chapter 4, Lists and pointer structures, and Chapter 13, Implementations, applications and tools.
Notice when we print out the key:value pairs of the dictionary it does so in no particular order. This is not a problem since we use specified keys to look up each dictionary value rather than an ordered sequence of integers as is the case for strings and lists.
- Android項(xiàng)目開發(fā)入門教程
- Redis Applied Design Patterns
- Mastering Swift 2
- 名師講壇:Java微服務(wù)架構(gòu)實(shí)戰(zhàn)(SpringBoot+SpringCloud+Docker+RabbitMQ)
- 程序員修煉之道:通向務(wù)實(shí)的最高境界(第2版)
- Java EE 8 Application Development
- 零基礎(chǔ)趣學(xué)C語言
- Haskell Data Analysis Cookbook
- ElasticSearch Cookbook(Second Edition)
- Python程序設(shè)計(jì)與算法基礎(chǔ)教程(第2版)(微課版)
- Java Web應(yīng)用開發(fā)給力起飛
- INSTANT JQuery Flot Visual Data Analysis
- 黑莓(BlackBerry)開發(fā)從入門到精通
- Python預(yù)測分析實(shí)戰(zhàn)
- Oracle Database XE 11gR2 Jump Start Guide