1. Create a dictionary with {}
Code:
| 12 |
x ={"a":"1", "b":"2"}printx |
Output:
{' A ': ' 1 ', ' B ': ' 2 '}
2, with the built-in function dict () 1), the entry parameter is similar to a= "1" the key value pair
Code:
| 12 |
x =dict(a="1", b="2")printx |
Output:
{' A ': ' 1 ', ' B ': ' 2 '}
2), the entry parameter is a tuple, within the tuple is a series of tuples containing two values, for example (("A", "1"), ("B", "2")
Code:
| 12 |
x =dict((("a", "1"), ("b", "2")))printx |
Output
{' A ': ' 1 ', ' B ': ' 2 '}
3), the entry is a tuple, within the tuple is a series of two values of the list, for example (["A", "1"], ["B", "2"])
Code:
| 12 |
x =dict((["a", "1"], ["b", "2"]))printx |
Output:
{' A ': ' 1 ', ' B ': ' 2 '}
4), enter the parameter as a list, inside the list is a series of tuples containing two values, for example [("A", "1"), ("B", "2")]
Code:
| 12 |
x =dict([("a", "1"),("b", "2")])printx |
Output:
{' A ': ' 1 ', ' B ': ' 2 '}
5), enter the parameter as a list, inside the list is a list of two values, for example [["A", "1"],["B", "2"]
Code:
| 12 |
x =dict([["a", "1"],["b", "2"]])printx |
Output:
{' A ': ' 1 ', ' B ': ' 2 '}
Attention:
For a= "1" to initialize the dictionary, the dictionary key can only be a string, and the string is not quoted
For dict built-in function initialization when the entry parameter is a tuple, for example 1), 2, two element tuples inside the tuple or the list is at least two, otherwise an error occurs
3, the user Fromkeys method to create a dictionary, the first
Code:
| 12 |
dict.fromkeys(("a", "b"), 1)printx |
Output:
{' A ': 1, ' B ': 1}
The first argument can be a list or tuple, the value of which is key, the second parameter is the value of all keys
A Dictionary of Python