Python Add to Dictionary: A Guide- Learn More

Humans are said to be creators. We can’t rest without creating something, and it is what pushes us forward and differentiates us from the rest. Never before has this been more true than in the twenty-first century.  A long time ago, even some 70 years ago, creation used to mean tangible, physical objects or machines that could be manufactured to make life better. Anyone with a computer and an internet connection may now make a difference in the cosmos. In this article, we are going to see about Python Add to Dictionary.

Bulky machines no longer dictate our lives. Instead, the balance of power has shifted to the intangible algorithms that make those machines work. Anyone with mastery over these algorithms can reshape the world in his image. This is where programming languages have opened the door for millions of people across the world. The pace of propagation of knowledge has accelerated in these past couple of years, all thanks to large sections of the population learning how to code. 

Python Add To dictionary

Python Programming Language: In Demand

Python is said to be the programming language of the present and future. This is because Python is easy to use. Python almost tries to replicate human speech and algorithms, which makes it easy to learn and code with. Gone are the days of complicated declarations, loops, and data structures. Python has managed to simplify all of that. And so, just like its namesake snake on its logo, Python Programming Language has slithered onto applications with far-reaching consequences. It is thanks to Python that we can find out if and how a machine or algorithm can think without specific directions from humans. This has given rise to python libraries which have powered the ascension of disciplines like Artificial Intelligence which include sub-sections like Machine Learning, Deep Learning, Natural Language Processing, and Neural Networks. By making programming as similar to human language as possible, python has quickly shot to the most preferred language that freshmen learn and use. This short article seeks to elucidate just how python simplifies work by shedding light on just a small part of it. 

Python Data Structures

Most programmers start by learning C and C++. As any amateur programming student could tell you, a key difference between python and C is the use of data structures. In C and C++, this means Linked Lists, Trees, and Graphs. Data Structures are meant to store information in such a manner that it is easily accessible. Python Data Structures include:

  • Lists
  • Dictionaries
  • Tuples
  • Sets 

The most unique data structure amongst the aforementioned is a dictionary. 

Jeff Bezos Career Advice
Jeff Bezos Career Advice

Python Data Structures: Dictionary: Key-Value Pairs

Python Dictionaries are unique from the other python data structures because of how they are accessed and updated. Lists are mutable and accessible using a variety of methods. Tuples are immutable and hence a bit difficult to update. Dictionaries, therefore, combine the best of both worlds to make it easier to access data and safely store it as well. As mentioned above, Dictionaries use a key-value system to store and access data. Unlike other data structures, Dictionaries store data in key-value pairs. Keys are used to access the values stored in a dictionary and are immutable and unique. A Dictionary can store any type of value. The values stored in a dictionary are both mutable and may be duplicated. This means that one can store just about anything in Dictionaries from Lists to other dictionaries. This also means that accessing and updating dictionaries is just a little bit different from other data structures. But first, let us learn how to create a dictionary:

Creating Dictionaries:

A dictionary is declared using curly parenthesis {}. Inside, key-value pairs are stored and differentiated using a colon- “:”. Different key-value pairs are stored one after another using commas- “,”. 

dict1= {1: ‘How’, 2: ‘Are’, 3: ‘You’}

dict2 = {‘Name’: ‘Joe’, 1: [1, 2, 3, 4]}

Here, everything to the left of the colon “:”, is a key, and everything to the right is the value associated with that key. The second Dictionary, dict2, represents a dictionary that has a list associated with the key “1”. 

These are some ways to initially add key-value pairs to dictionaries while creating them. Updating and adding key-value pairs to Dictionaries is a whole different ball game that has its own functions involved. 

Adding Items to a Dictionary in Python

Just like other data structures, Python also has a number of ways in which key-value pairs can be added to a Dictionary. 

Using square parenthesis “[]” to access the Dictionary and add key-value pairs

One can update existing values by accessing the key for that value using a square parenthesis “[]” to the right of the Dictionary name, with the key written inside and the updated value to the right of the equals “=” sign. Similarly, this method can also be used for adding new key-value pairs to the Dictionary simply by writing the new key inside the square parenthesis “[]”. 

dict1= {1: ‘How’, 2: ‘Are’, 3: ‘You’}

dict1[4] = ‘Today’

This will add a 4th element to the Dictionary with its key as “4” and the value associated with the key as “Today”. Note that keys in a dictionary may have any data type. One may also make use of strings for keys, provided that the string is enclosed within quotation marks- “ ”. Numbers are not required to be enclosed within quotation marks. The same applies to the values associated with the keys. 

E.g.: dict1[“Hello”] = 3

The above command will add a value “3” to the Dictionary dict1, with a key “Hello”.

Using the update() function

Similar to the last method, the update() function can also be used to update or change the value of an existing key or add a new key-value pair. The same rules regarding data types and quotation marks also apply to the update() function. The update() function is a built-in function for data structures like Lists and Dictionaries in python. It takes a key-value pair inside of a parenthesis “{}” and is separated by a colon- “:”. It updates the value for a consequent existing key or adds the pair if the key is not present in the original Dictionary. There are various possible ways to use the update() function, and all of them have minor discrepancies in syntax. 

car = {

   “brand”: “Ford”,

   “model”: “Figo”,

   “year”: 2020

 }

 car.update({“color”: “red”})

The above example illustrates how the update() function works. The function takes in the key-value pair “color: red” inside the parenthesis “{}” and the normal brackets “()”. Both the pairs are strings and not numbers and are hence enclosed in quotation marks “ ”. As the key “color” isn’t present in the original Dictionary “car”, a new key-value pair is added to the Dictionary. 

car.update(dict(tyres= 4))

Here, the value 4 is associated with the key “tires” and is added to the Dictionary car using update(). An equal sign “=” is used to represent this association instead of the colon “:” and both the parenthesis “{}” and the quotation marks “ ” are excluded. 

car.update(number=1)

Note:

Keys cannot be duplicated and are immutable. The only possible way to change a key is to go to the definition of the Dictionary and manually change the name of the key. In the above two methods, if one tries to add a key-value pair whose key already exists in the original Dictionary, then the Dictionary simply changes the value of that existing key and doesn’t add a separate key to itself. 

Method 1: 

dict1= {1: ‘How’, 2: ‘Are’, 3: ‘You’}

dict1[3] = ‘Today’

The key “3” already exists in the Dictionary, and so, the above command will simply change the value associated with the key “3” from “You” to “Today”. 

Method 2:

car = {

   “brand”: “Ford”,

   “model”: “Figo”,

   “year”: 2020

 }

 car.update({“brand”: “Honda”})

As the key “brand” already exists in the Dictionary “car”, the above code will simply change the value associated with the key “brand” from “Ford” to “Honda” using the update() function. 

Adding or updating multiple values in a Dictionary

The above methods for adding one key-value pair to an existing Dictionary can also be used for adding multiple key-value pairs. Here, a comma “,” is used to separate one key-value pair from another. 

data.update({‘c’:3,’d’:4})

The above code adds the keys “c” and “d” to the Dictionary data, with values 3 and 4, respectively.

Using append() function

One can also use the in-built function append() to insert values to existing keys or add new key-value pairs to the Dictionary. The value is entered inside the append() function, and the key is specified alongside the Dictionary inside square parenthesis “[]”.  

dict = {“Name”:[],”Address”:[],”Age”:[]};

dict[“Name”].append(“Joe”)

dict[“Address”].append(“New York”)

dict[“Age”].append(30)     

In the above example, the value “Joe” is inserted inside the Dictionary associated with the key “Name” using the append() function. The same is true for “New York” being associated with the key “Address”. 

Using _setitem_

A lesser-known and lesser-used method of adding a key-value pair inside a Dictionary is by using _setitem_. The syntax of the _setitem_ method is similar to the update function wherein the key-value pair is entered inside the parenthesis. The _setitem_ function takes in the key and the value associated with that key. The only difference is in the “,” that separates the key from the value. 

dict = {‘key1′:’My’, ‘key2′:’Name’}

dict.__setitem__(‘new’, ‘is’)

Here, the key to be entered into the Dictionary “dict” is “new”, and the value associated with that key is “is”. This method, however, is not considered to be computationally efficient and should preferably be avoided in most cases. 

Operator 

Using this method, the user can merge an existing Dictionary and a new key/value pair in another Dictionary. The “**” operator is used before the name of the old Dictionary and the new key-value pairs while creating the new Dictionary. 

dict = {‘a’: 1, ‘b’: 2}

new_dict = {**dict, **{‘c’: 3}}

Here, the new key-value pair is “c:3”, and it is merged with the existing Dictionary “dict” to form a new Dictionary “new_dict” using the “**” operator. 

Using the dict() function

Python has an inbuilt dict() function, which can be used to create a Dictionary. In this method, an equal’s sign “=” is used to designate the values to their respective keys instead of a colon “:”.

x = dict(name = “Joe”, age = 31, country = “USA”)

As shown above, the dict() function takes in key-value pairs as inputs and creates a Dictionary out of them. 

Adding other data structures to a Dictionary

As mentioned above, Python has a number of built-in data structures which make it easier to store data. These include Lists, Tuples, Sets, and Dictionaries. Dictionaries can also store values in the form of all of these data structures. The easiest way to add other data structures to a Dictionary is to first declare the data structures separately and then add them to the Dictionary by just associating their names to keys in the Dictionary. One can then add items to the data structures separately, and they will automatically get updated in the Dictionary. 

list=[]

tuple=()

dict3={1: list, 2: tuple}

list.append(1)

list.append(2)

tuple.append(10)

tuple.append(20)

In the above example, the Dictionary contains a List associated with the key “1”, and a tuple associated with the key “2”. The values appended in “list” and “tuple” are also added to the Dictionary “dict”. One can also add Dictionaries to an existing Dictionary (nested Dictionaries). 

Dict = {}

Dict = { ‘Dict1’: {}, 

         ‘Dict2’: {}}

Dict[‘Dict1’][‘name’] = ‘Rob’

Dict[‘Dict1’][‘age’] = 22

Dict[‘Dict2’] = {‘name’: ‘Cara’, ‘age’: 25}

Here, both Dictionaries “Dict1” and “Dict2” are added to “Dict”. The key-value pairs “name:Rob” and “age:22” are then inserted into “Dict1” using square parenthesis “[]”. From this, we can also deduce how to access the elements of a Nested Dictionary i.e., by using two sets of square parentheses “[]”. The first to access the key associated with the Nested Dictionary inside the main Dictionary, and the second to access the keys inside the Nested Dictionary. In the above case, “Dict1” is the key associated with the 1st Dictionary, and “name” and “age” are keys inside of the Nested Dictionary “Dict1”. 

Advantages of a Dictionary

  1. Using a Dictionary makes the program more organized and easier to read. 
  2. Data is stored and accessed more efficiently because of the key-value system. One can access the items in a Dictionary simply by referring to its key. 
  3. A Dictionary can store any type of data structure, even other Dictionaries. 

Practice Makes Perfect (Conclusion) 

A Dictionary forms a vital cog in Python Programming basics. The key-value system makes it easier to access items while not making it too hard to add items. While there are many ways and methods to add or update the items of a Dictionary, all of them are correct and more or less similar in implementation and syntax. Mastering the science of how Dictionaries work and how to add items to a Dictionary in different situations can lay a firm footing for future mastery of Python. This is just the first step, and we advise you to build on this by rigorous practice. 

Frequently Asked Questions 

  1. Which is the easiest method of adding items to a Dictionary?

– While all the methods mentioned above work just fine, amateur programmers often start by learning about the first method, which allows a user to add or update a key-value pair by referring to its key in square parenthesis “[]”.  

  1. How can one find all the keys in a Dictionary?

– Python has an in-built function “keys()” which provides the user with a List of the Dictionary’s keys. 

  1. How do I remember all these methods of inserting items into a Dictionary?

– The most important thing to remember about a Dictionary is the key-value system. It will suffice for a new programmer to remember one or two of the methods mentioned above. This can be done by practicing the adding of items into a Dictionary in real-time. 

Python Add to Dictionary: A Guide- Learn More

Leave a Reply

Your email address will not be published.

Scroll to top
Land your Dream Job
Get actional first hand insights from people who share their job search stories.