Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js

Important Topics Continue:

6. Dictionaries :

Python dictionaries are something completely different —they are not sequences at all, but are instead known as mappings.
Mappings are also collections of other objects, but they store objects by key instead of by relative position.
Dictionaries are coded in curly braces and consist of a series of “key: value” pairs.
Dictionaries are useful anytime we need to associate a set of values with keys—to describe the properties of something,
As an example, consider the following three-item dictionary (with keys “food,” “quantity,” and “color,” perhaps the details of a hypothetical menu item?):

>>> D = {'food': 'Spam', 'quantity': 4, 'color': 'pink'}

>>> D['food']              # Fetch value of key 'food'
'Spam'
>>> D['quantity'] += 1     # Add 1 to 'quantity' value
>>> D
{'color': 'pink', 'food': 'Spam', 'quantity': 5}

>>> D = {}
>>> D['name'] = 'Bob'      # Create keys by assignment
>>> D['job']  = 'dev'
>>> D['age']  = 40
>>> D
{'age': 40, 'job': 'dev', 'name': 'Bob'}
>>> print(D['name'])
Bob

We can also make dictionaries by passing to the dict type name either keyword arguments (a special name=value syntax in function calls)
>>> bob1 = dict(name='Bob', job='dev', age=40)                      
>>> bob1
{'age': 40, 'name': 'Bob', 'job': 'dev'}

>>> bob2 = dict(zip(['name', 'job', 'age'], ['Bob', 'dev', 40]))    # Zipping
>>> bob2
{'job': 'dev', 'name': 'Bob', 'age': 40}

 

Untitled

Bhavuk kumar
Module by Bhavuk kumar, updated more than 1 year ago
No tags specified