in Python by
Q:
How Do You Add Elements To A Dictionary In Python?

1 Answer

0 votes
by
We can add elements by modifying the dictionary with a fresh key and then set the value to it.

>>> # Setup a blank dictionary

>>> site_stats = {}

>>> site_stats['site'] = 'google.com'

>>> site_stats['traffic'] = 10000000000

>>> site_stats['type'] = 'Referral'

>>> print(site_stats)

{'type': 'Referral', 'site': 'google.com', 'traffic': 10000000000}

We can even join two dictionaries to get a bigger dictionary with the help of the update() method.

>>> site_stats['site'] = 'google.co.in'

>>> print(site_stats)

{'site': 'google.co.in'}

>>> site_stats_new = {'traffic': 1000000, "type": "social media"}

>>> site_stats.update(site_stats_new)

>>> print(site_stats)

{'type': 'social media', 'site': 'google.co.in', 'traffic': 1000000}

Related questions

0 votes
asked Dec 19, 2019 in Python by sharadyadav1986
0 votes
asked Aug 30, 2020 in Python by sharadyadav1986
...