Python dict() function is used to create a dictionary. A dictionary is different than a list, it is a set of key-value pairs.
Each key has a unique value and you can quickly get a value using the key. Keys must be unique, but values don't need to be.
In older versions of Python dictionaries were not in insertion order, but with the newest Python they are.
Syntax
The dict() function syntax is:
class dict(** kwarg)
class dict(mapping, ** kwarg)
class dict(iterable, ** kwarg)
Parameter Description:
- kwargs: Keyword
- Mapping: container elements.
- Iterable: iterables.
return value
Returns a dictionary.
examples
The following example demonstrates the use of dict:
>>> dict() # Create an empty dictionary
{}
>>> dict(a = 'a', b = 'b', t = 't') # incoming keyword
{ 'A': 'a', 'b': 'b', 't': 't'}
>>>
>>> dict(zip ([ 'one', 'two', 'three'], [1, 2, 3]))
{ 'Three': 3, 'two': 2, 'one': 1}
>>>
>>> dict([( 'one', 1), ( 'two', 2), ( 'three', 3)])
{ 'Three': 3, 'two': 2, 'one': 1}
>>>
>>>
After creation of the dictionary, you can retrieve values or loop over it.
>>> m = dict([( 'one', 1), ( 'two', 2), ( 'three', 3)])
>>> m['one']
1
>>> m['two']
2
>>> m['three']
3
>>> for k, v in m.items():
... print(f"{k} => {v}")
...
one => 1
two => 2
three => 3
>>>
Related links:
Top comments (0)