Dict() Function In Python

Function Name:

dict

 

Function Signature:

class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

 

Function Overview:

  • The dict() function is a constructor to the Python dict class.
  • dict() function constructs and returns the dictionary objects.
  • Dictionaries are used to hold key, value pairs.
  • A dictionary is a mapping type in Python - it has keys mapped to values.
  • The Python dict class represents a dictionary.
  • dict objects are mutable, that is mappings can be added and removed from a dictionary instance.

 

Example1:

electronCount = {"hydrogen":1,

                 "helium": 2,

                 "lithium":3

                }

               

print("Number of electrons a hydrogen atom has:{}".format(electronCount["hydrogen"]))

 

print("Number of electrons a helium atom has:{}".format(electronCount["helium"]))

 

print("Number of electrons a lithium atom has:{}".format(electronCount["lithium"]))

 

 

Output:

Number of electrons a hydrogen atom has:1

Number of electrons a helium atom has:2

Number of electrons a lithium atom has:3

 

Example2:

# Build list of countries - ISO code vs Name of the country

countryCodes = {"CA":"Canada",

                "US":"United States of America",

                "MX":"Mexico"

                }

               

print("Country Codes : {}".format(countryCodes))

 

# Add more countries countries

countryCodes["CU"] = "Cuba"

countryCodes["JM"] = "Jamaica"

 

print("Country Codes : {}".format(countryCodes))

 

 

Output:

Country Codes : {'CA': 'Canada', 'US': 'United States of America', 'MX': 'Mexico'}

Country Codes : {'CA': 'Canada', 'US': 'United States of America', 'MX': 'Mexico', 'CU': 'Cuba', 'JM': 'Jamaica'}

 

 


Copyright 2018 © pythontic.com