Python dict (Dictionary) Data Type

Python dict (dictionary) is a collection of key-value pairs.

>>> quote = {
...     'open' : 9.54, 
...     'high' : 9.71, 
...     'low' : 9.49, 
...     'close' : 9.62
... }
...
>>> quote
{'open': 9.54, 'high': 9.71, 'low': 9.49, 'close': 9.62}
>>> type(quote)
<class 'dict'>

You can find a value by its key:

>>> quote['close']
9.62

You can also change a value by its key:

>>> quote['close'] = 9.63
>>> quote
{'open': 9.54, 'high': 9.71, 'low': 9.49, 'close': 9.63}

You can add a new key-value pair in the same way:

>>> quote['volume'] = 10855
>>> quote
{'open': 9.54, 'high': 9.71, 'low': 9.49, 'close': 9.63, 'volume': 10855}

Keys must be unique, values can be duplicate.

>>> quote = {
...     'open' : 9.71, 
...     'high' : 9.71, 
...     'low' : 9.49, 
...     'close' : 9.62
... }

Values can be of different types.

>>> quote = {
...     'open' : 999999, 
...     'high' : None, 
...     'low' : 'No idea', 
...     'close' : 9.62
... }

Keys can also be of different types (they must still be unique).

>>> various = {
...     'open' : 'This key is a string',
...     'high' : 'This key is another string',
...     123 : 'This key is an int', 
...     123.456 : 'This key is a float', 
...     True : 'This key is a bool'
... }

By remaining on this website or using its content, you confirm that you have read and agree with the Terms of Use Agreement.

We are not liable for any damages resulting from using this website. Any information may be inaccurate or incomplete. See full Limitation of Liability.

Content may include affiliate links, which means we may earn commission if you buy on the linked website. See full Affiliate and Referral Disclosure.

We use cookies and similar technology to improve user experience and analyze traffic. See full Cookie Policy.

See also Privacy Policy on how we collect and handle user data.

© 2024 PyTut