Tags
Asked 2 years ago
5 Aug 2021
Views 248
Joesph

Joesph posted

How do you declare a dictionary in Python 3 ?

How do you declare a dictionary in Python 3 ?
andy

andy
answered Aug 8 '21 00:00

1.dictionary can be declared by type constructor in Python 3

dict() used for create dictionary . dict() is work like constructor.

c=dict()

dict() will create empty dictionary


c=dict([('a',1000), ['d','e'],('b', 2000)])
print(c)

it will create dictionary like this {'a': 1000, 'd': 'e', 'b': 2000}

same dictionary can be created like this
d=dict(a=1000,d='e',b=2000)

2. {} comma-separated list of key: value pairs within braces can be used to create Dictionary in Python 3
one can use {} for the creating of the empty dictionary
or
d={'a': 1000, 'd': 'e', 'b': 2000} - Use a comma-separated list of key: value pairs within braces

3. Use dict comprehension to declare a dictionary in Python 3

j={x: x+2 for x in range(10)}
print(j)


it will print
{0: 2, 1: 3, 2: 4, 3: 5, 4: 6, 5: 7, 6: 8, 7: 9, 8: 10, 9: 11}

Post Answer