'Can both the values and keys of a dictionary be integers?

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?



Solution 1:[1]

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)}

Solution 2:[2]

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.

Solution 3:[3]

Any immutable can be dictionary key. like string , number, tuple etc. the type which cannot be keys are mutable entity like list, set etc.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2
Solution 3 Mayank Jain