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:
committed by
Manish Giri
parent
328710238e
commit
a62a30ce63
@ -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.
|
||||
|
||||
The special thing about dictionaries is the way they are implemented. Hash-table-like structure makes it easy to check for
|
||||
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.
|
||||
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.
|
||||
|
||||
Dictionaries can use almost any arbitrary datatypes, like strings, integers etc, for keys. However, values that are not hashable,
|
||||
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.)
|
||||
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.
|
||||
|
||||
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:
|
||||
```python
|
||||
>>> teams = {}
|
||||
>>> teams = {} # Creates a empty dictionary
|
||||
>>> type(teams)
|
||||
>>> <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:
|
||||
```python
|
||||
>>> teams = {'barcelona': 1875, 'chelsea': 1910}
|
||||
>>> teams
|
||||
{'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
|
||||
>>> teams['santos'] = 1787
|
||||
>>> teams
|
||||
@ -34,16 +60,24 @@ It's easy to add key-value pairs to an existing dictionary:
|
||||
>>> teams['barcelona']
|
||||
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.
|
||||
```python
|
||||
>>> del teams['santos']
|
||||
>>> teams
|
||||
{'chelsea': 1910, 'barcelona': 1875}
|
||||
```
|
||||
## Replacing Value of a Key in a Dictionary
|
||||
|
||||
```python
|
||||
>>> teams['chelsea'] = 2017 # overwriting
|
||||
>>> teams
|
||||
{'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
|
||||
>>> 'sanots' in teams
|
||||
@ -53,6 +87,8 @@ It's easy to add key-value pairs to an existing dictionary:
|
||||
>>> 'chelsea' not in teams
|
||||
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:
|
||||
```python
|
||||
>>> 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)}
|
||||
{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:
|
||||
```python
|
||||
>>> 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
|
||||
z
|
||||
```
|
||||
To loop over both key and value you can use the following:
|
||||
For Python 2.x:
|
||||
**Looping in Dictionary for Python Version 2**
|
||||
|
||||
To loop over both keys and values you can use the following:
|
||||
```python
|
||||
>>> for key, item in d.iteritems():
|
||||
... print items
|
||||
@ -112,7 +149,9 @@ For Python 2.x:
|
||||
2
|
||||
3
|
||||
```
|
||||
Use **`items()`** for Python 3.x:
|
||||
**Looping in Dictionary for Python Version 3**
|
||||
|
||||
Use **`items()`** instead of **iteeritems()**:
|
||||
```python
|
||||
>>> for key, item in d.items():
|
||||
... print(key, items)
|
||||
|
Reference in New Issue
Block a user