Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: create dictionary using dict() with integer keys?

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?

like image 971
Sindyr Avatar asked Sep 12 '15 23:09

Sindyr


People also ask

Can I use integer as key in dictionary Python?

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.

Can dict keys be numbers?

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."

How do you create a dictionary using keys and values?

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.

How do you create a dictionary in Python?

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.


1 Answers

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."

like image 98
BrenBarn Avatar answered Sep 20 '22 17:09

BrenBarn