Categories

Dec 19, 2019 in Python

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

1 Answer

Dec 19, 2019
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}
Click here to read more about Python
Click here to read more about Insurance

Related questions

Madanswer
Dec 19, 2019 in Python
Aug 30 in Python
Dec 22, 2019 in Python
...