In Python, I see people creating dictionaries like this:
d = dict( one = 1, two = 2, three = 3 )
What if my keys are integers? When I try this:
d = dict (1 = 1, 2 = 2, 3 = 3 )
I get an error. Of course I could do this:
d = { 1:1, 2:2, 3:3 }
which works fine, but my main question is this: is there a way to set integer keys using the dict() function/constructor?
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.
Yes. "...can be any immutable type; strings and numbers can always be keys..." Literally from the link you posted: "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."
To create a Python dictionary, we pass a sequence of items (entries) inside curly braces {} and separate them using a comma ( , ). Each entry consists of a key and a value, also known as a key-value pair. Note: The values can belong to any data type and they can repeat, but the keys must remain unique.
In Python, a dictionary can be created by placing a sequence of elements within curly {} braces, separated by 'comma'. Dictionary holds pairs of values, one being the Key and the other corresponding pair element being its Key:value.
Yes, but not with that version of the constructor. You can do this:
>>> dict([(1, 2), (3, 4)]) {1: 2, 3: 4}
There are several different ways to make a dict. As documented, "providing keyword arguments [...] only works for keys that are valid Python identifiers."
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