Can both the values and keys of a dictionary be integers in python? Or do I need one of them to be like a string or something?
Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable.
Valid keysThe keys of a dictionary can be any kind of immutable type, which includes: strings, numbers, and tuples: mydict = {"hello": "world", 0: "a", 1: "b", "2": "not a number" (1, 2, 3): "a tuple!"}
Practical Data Science using Python Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
Define a Dictionary Values are in blue. The dictionary webstersDict used strings as keys in the dictionary, but dictionary keys can be any immutable data type (numbers, strings, tuples etc). Dictionary values can be just about anything (int, lists, functions, strings, etc).
Sure! From the python docs:
5.5. Dictionaries
Another useful data type built into Python is the dictionary (see Mapping Types — dict). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
You can also try it out super quickly:
>>> dict = {1:0, 2:1}
>>> dict[1]
0
>>> dict[2]
1
I like one of the examples on the page as it uses a dictionary comprehension (new in 2.7+) in a way that works like a function:
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
Since it works for any immutable type you can even use floats for keys:
>>> {x: x**2 for x in (1, 1.5, 2)}
{1: 1, 1.5: 2.25, 2: 4}
And again, another common immutable type in python are tuples, (..., ..., ...)
which you can also use for keys:
>>> {(x,y): (x**2,y**2) for x in range(3) for y in range(2)}
{(0, 0): (0, 0),
(0, 1): (0, 1),
(1, 0): (1, 0),
(1, 1): (1, 1),
(2, 0): (4, 0),
(2, 1): (4, 1)}
Of course. Just take a very simple example: in python interpreter, input:
a = {1:2} # define an dict
a[1] # get the value whose key is 1
then you will get out put 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With