Rephrasing the guide on how a dictionary works in Python for a layman. (#23949)

* Rephrasing on how a dictionary works in Python 

Rephrased the guide to make it easier to understand for a layman. Besides that added headers to break it down further to explain certain aspects of the python dictionary.

* Update guide/english/python/data-structures/dictionaries/index.md

Co-Authored-By: steelwolf180 <steelwolf180@gmail.com>

* Update guide/english/python/data-structures/dictionaries/index.md

Co-Authored-By: steelwolf180 <steelwolf180@gmail.com>

* Update guide/english/python/data-structures/dictionaries/index.md

Co-Authored-By: steelwolf180 <steelwolf180@gmail.com>

* Update guide/english/python/data-structures/dictionaries/index.md

Co-Authored-By: steelwolf180 <steelwolf180@gmail.com>

* Redo my previous delete

Undo my deleting of **has_key()** method
This commit is contained in:
Max Ong Zong Bao
2018-12-20 04:39:01 +08:00
committed by Manish Giri
parent 328710238e
commit a62a30ce63

View File

@ -4,27 +4,53 @@ title: The Python Dict
A Dictionary (a.k.a "dict") in python is a built-in datatype that can be used to store **`key-value`** pairs. This allows you to treat a **`dict`** like it's a *database* to store and organize data. A Dictionary (a.k.a "dict") in python is a built-in datatype that can be used to store **`key-value`** pairs. This allows you to treat a **`dict`** like it's a *database* to store and organize data.
The special thing about dictionaries is the way they are implemented. Hash-table-like structure makes it easy to check for The special thing about dictionaries is the way they are implemented. It's similar to how a filing cabinet works. By just specifying the **key** which is like a book title, the python interpreter can just go to the location of the key and check for the content (**value**) of that key.
existence - which means that we can easily determine if a specific key is present in the dictionary without needing to examine
every element. The Python interpreter can just go to the location key and check if the key is there.
Dictionaries can use almost any arbitrary datatypes, like strings, integers etc, for keys. However, values that are not hashable, Dictionaries can use almost any datatypes, like strings, integers etc, as the key of dictionaries. However, values that are not hashable, such as, *lists*, *dictionaries* or other mutable types (that are compared by value rather than by object identity) may not be used as keys.
that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (such as `1` and `1.0`) then they can be used interchangeably to index the same dictionary entry. (Note however, that since computers store floating-point numbers as approximations it is usually unwise to use them as dictionary keys.)
Numeric types used for keys obey the normal rules for numeric comparison. For example if two numbers compare equal (such as `1` and `1.0`) then they can be used interchangeably to index the same dictionary entry.
(Note, however, that since computers store floating-point numbers as approximations it is usually unwise to use them as dictionary keys.)
An important requirement of a dictionary is that the keys *must* be *unique*, which means - you can never have a duplicate key in your dictionary.
## Creating a Empty Dictionary
One most important requirement of a dictionary is that the keys **must** be unique.
To create an empty dictionary just use a pair of braces: To create an empty dictionary just use a pair of braces:
```python ```python
>>> teams = {} >>> teams = {} # Creates a empty dictionary
>>> type(teams) >>> type(teams)
>>> <class 'dict'> >>> <class 'dict'>
``` ```
## Creating a Non-Empty Dictionary
To create a non-empty dictionary with some initial values, place a comma-seperated list of key-value pairs: To create a non-empty dictionary with some initial values, place a comma-seperated list of key-value pairs:
```python ```python
>>> teams = {'barcelona': 1875, 'chelsea': 1910} >>> teams = {'barcelona': 1875, 'chelsea': 1910}
>>> teams >>> teams
{'barcelona': 1875, 'chelsea': 1910} {'barcelona': 1875, 'chelsea': 1910}
``` ```
It's easy to add key-value pairs to an existing dictionary: ## Alternative Ways To Create a Dictionary
You could create a dictionary by using the **`dict()`** method:
```python
>>> players = dict( [('messi','argentina'), ('ronaldo','portugal'), ('kaka','brazil')] ) # sequence of key-value pair is passed
>>> players
{'ronaldo': 'portugal', 'kaka': 'brazil', 'messi': 'argentina'}
>>>
>>> # If keys are simple strings, it's quite easier to specify pairs using keyword arguments
...
>>> dict( totti = 38, zidane = 43 )
{'zidane': 43, 'totti': 38}
```
Dict comprehensions can be used as well to create dictionaries from arbitrary key and value expressions:
```python
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
```
## Adding New Key-Vaule Pair to Existing Dictionary
```python ```python
>>> teams['santos'] = 1787 >>> teams['santos'] = 1787
>>> teams >>> teams
@ -34,16 +60,24 @@ It's easy to add key-value pairs to an existing dictionary:
>>> teams['barcelona'] >>> teams['barcelona']
1875 1875
``` ```
## Deleting a Key-Value Pair From a Dictionary
**`del`** operator is used to delete a key-value pair from the dict. In scenarios where a key that's already in use is again used to store values, the old value associated with that key is completely lost. Also, keep in mind that it's an error to extract the value using an non-existent key. **`del`** operator is used to delete a key-value pair from the dict. In scenarios where a key that's already in use is again used to store values, the old value associated with that key is completely lost. Also, keep in mind that it's an error to extract the value using an non-existent key.
```python ```python
>>> del teams['santos'] >>> del teams['santos']
>>> teams >>> teams
{'chelsea': 1910, 'barcelona': 1875} {'chelsea': 1910, 'barcelona': 1875}
```
## Replacing Value of a Key in a Dictionary
```python
>>> teams['chelsea'] = 2017 # overwriting >>> teams['chelsea'] = 2017 # overwriting
>>> teams >>> teams
{'chelsea': 2017, 'barcelona': 1875} {'chelsea': 2017, 'barcelona': 1875}
``` ```
**`in`** keyword can be used to check whether a key exist in the dict or not: ## Searching for Existing Keys in a Dictionary
The **`in`** keyword can be used to check whether a key exist in the dict or not:
```python ```python
>>> 'sanots' in teams >>> 'sanots' in teams
@ -53,6 +87,8 @@ It's easy to add key-value pairs to an existing dictionary:
>>> 'chelsea' not in teams >>> 'chelsea' not in teams
False False
``` ```
## Getting All of the Keys or Values In the Dictionary
**`keys`** is a built-in *method* that can be used to get the keys of a given dictionary. To extract the keys present in a dict as lists: **`keys`** is a built-in *method* that can be used to get the keys of a given dictionary. To extract the keys present in a dict as lists:
```python ```python
>>> club_names = list(teams.keys()) >>> club_names = list(teams.keys())
@ -90,8 +126,8 @@ Dict comprehensions can be used as well to create dictionaries from arbitrary ke
>>> {x: x**2 for x in (2, 4, 6)} >>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36} {2: 4, 4: 16, 6: 36}
``` ```
**Looping in Dictionary** ## Looping in Dictionary
To simply loop over the keys in the dictionary, rather than the keys and values: To simply loop over the keys in the dictionary, rather than the keys and values:
```python ```python
>>> d = {'x': 1, 'y': 2, 'z': 3} >>> d = {'x': 1, 'y': 2, 'z': 3}
@ -102,8 +138,9 @@ To simply loop over the keys in the dictionary, rather than the keys and values:
y y
z z
``` ```
To loop over both key and value you can use the following: **Looping in Dictionary for Python Version 2**
For Python 2.x:
To loop over both keys and values you can use the following:
```python ```python
>>> for key, item in d.iteritems(): >>> for key, item in d.iteritems():
... print items ... print items
@ -112,7 +149,9 @@ For Python 2.x:
2 2
3 3
``` ```
Use **`items()`** for Python 3.x: **Looping in Dictionary for Python Version 3**
Use **`items()`** instead of **iteeritems()**:
```python ```python
>>> for key, item in d.items(): >>> for key, item in d.items():
... print(key, items) ... print(key, items)