banner



How To Add Elements To An Empty Dictionary In Python

Create a Dictionary in Python – Python Dict Methods

In this article, you volition acquire the basics of dictionaries in Python.

Y'all will larn how to create dictionaries, access the elements inside them, and how to modify them depending on your needs.

You will also learn some of the most mutual built-in methods used on dictionaries.

Hither is what we will cover:

  1. Define a dictionary
    1. Define an empty dictionary
    2. Define a dictionary with items
  2. An overview of keys and values
    1.Find the number of key-value pairs contained in a dictionary
    2.View all fundamental-value pairs
    3.View all keys
    four.View all values
  3. Access private items
  4. Modify a dictionary
    1. Add together new items
    2. Update items
    3. Delete items

How to Create a Lexicon in Python

A dictionary in Python is made up of key-value pairs.

In the 2 sections that follow you lot will run into 2 means of creating a dictionary.

The first way is by using a set of curly braces, {}, and the 2nd fashion is by using the built-in dict() function.

How to Create An Empty Lexicon in Python

To create an empty dictionary, outset create a variable name which will be the proper noun of the dictionary.

Then, assign the variable to an empty gear up of curly braces, {}.

                #create an empty lexicon my_dictionary = {}  print(my_dictionary)  #to check the data type use the blazon() office print(type(my_dictionary))  #output  #{} #<grade 'dict'>                              

Some other way of creating an empty dictionary is to use the dict() function without passing any arguments.

Information technology acts as a constructor and creates an empty lexicon:

                #create an empty dictionary my_dictionary = dict()  print(my_dictionary)  #to bank check the information type utilize the type() function print(type(my_dictionary))  #output  #{} #<class 'dict'>                              

How to Create A Dictionary With Items in Python

To create a lexicon with items, you need to include central-value pairs inside the curly braces.

The general syntax for this is the post-obit:

                dictionary_name = {key: value}                              

Let'south break it downwards:

  • dictionary_name is the variable name. This is the proper noun the dictionary volition have.
  • = is the assignment operator that assigns the key:value pair to the dictionary_name.
  • You declare a dictionary with a set of curly braces, {}.
  • Within the curly braces you accept a key-value pair. Keys are separated from their associated values with colon, :.

Let's see an instance of creating a dictionary with items:

                #create a dictionary my_information = {'proper name': 'Dionysia', 'age': 28, 'location': 'Athens'}  impress(my_information)  #check data type print(blazon(my_information))  #output  #{'name': 'Dionysia', 'age': 28, 'location': 'Athens'} #<form 'dict'>                              

In the example above, there is a sequence of elements inside the curly braces.

Specifically, in that location are 3 key-value pairs: 'name': 'Dionysia', 'age': 28, and 'location': 'Athens'.

The keys are name, historic period, and location. Their associated values are Dionysia, 28, and Athens, respectively.

When in that location are multiple central-value pairs in a dictionary, each key-value pair is separated from the next with a comma, ,.

Allow's see another example.

Say that you want to create a lexicon with items using the dict() function this fourth dimension instead.

You would accomplish this past using dict() and passing the curly braces with the sequence of key-value pairs enclosed in them as an argument to the function.

                #create a dictionary with dict() my_information = dict({'name': 'Dionysia' ,'historic period': 28,'location': 'Athens'})  impress(my_information)  #check data blazon print(type(my_information))  #output  #{'proper name': 'Dionysia', 'age': 28, 'location': 'Athens'} #<class 'dict'>                              

It'south worth mentioning the fromkeys() method, which is another way of creating a dictionary.

It takes a predefined sequence of items equally an statement and returns a new lexicon with the items in the sequence prepare as the dictionary's specified keys.

Yous can optionally set a value for all the keys, but past default the value for the keys will be None.

The general syntax for the method is the following:

                dictionary_name = dict.fromkeys(sequence,value)                              

Permit'south see an case of creating a lexicon using fromkeys() without setting a value for all the keys:

                #create sequence of strings cities = ('Paris','Athens', 'Madrid')  #create the dictionary, `my_dictionary`, using the fromkeys() method my_dictionary = dict.fromkeys(cities)  impress(my_dictionary)  #{'Paris': None, 'Athens': None, 'Madrid': None}                              

At present allow'south see another example that sets a value that will be the same for all the keys in the dictionary:

                #create a sequence of strings cities = ('Paris','Athens', 'Madrid')  #create a single value continent = 'Europe'  my_dictionary = dict.fromkeys(cities,continent)  impress(my_dictionary)  #output  #{'Paris': 'Europe', 'Athens': 'Europe', 'Madrid': 'Europe'}                              

An Overview of Keys and Values in Dictionaries in Python

Keys within a Python dictionary can only be of a type that is immutable.

Immutable data types in Python are integers, strings, tuples, floating indicate numbers, and Booleans.

Dictionary keys cannot exist of a type that is mutable, such as sets, lists, or dictionaries.

So, say yous accept the post-obit dictionary:

                my_dictionary = {True: "True",  one: 1,  1.i: 1.one, "one": 1, "languages": ["Python"]}  print(my_dictionary)  #output  #{Truthful: i, ane.1: ane.1, 'ane': 1, 'languages': ['Python']}                              

The keys in the dictionary are Boolean, integer, floating point number, and string information types, which are all acceptable.

If you try to create a fundamental which is of a mutable type you'll become an error - specifically the fault will exist a TypeError.

                my_dictionary = {["Python"]: "languages"}  print(my_dictionary)  #output  #line 1, in <module> #    my_dictionary = {["Python"]: "languages"} #TypeError: unhashable type: 'list'                              

In the instance higher up, I tried to create a key which was of listing blazon (a mutable information blazon). This resulted in a TypeError: unhashable blazon: 'listing' error.

When it comes to values inside a Python dictionary there are no restrictions. Values can be of any data blazon - that is they can be both of mutable and immutable types.

Another thing to note about the differences between keys and values in Python dictionaries, is the fact that keys are unique. This means that a key can simply appear once in the dictionary, whereas at that place can be duplicate values.

How to Notice the Number of fundamental-value Pairs Contained in a Dictionary in Python

The len() function returns the total length of the object that is passed every bit an argument.

When a lexicon is passed as an argument to the function, it returns the full number of key-value pairs enclosed in the dictionary.

This is how you calcualte the number of key-value pairs using len():

                my_information = {'name': 'Dionysia', 'age': 28, 'location': 'Athens'}  print(len(my_information))  #output  #3                              

How to View All key-value Pairs Contained in a Dictionary in Python

To view every central-value pair that is within a dictionary, use the built-in items() method:

                year_of_creation = {'Python': 1993, 'JavaScript': 1995, 'HTML': 1993}  print(year_of_creation.items())  #output  #dict_items([('Python', 1993), ('JavaScript', 1995), ('HTML', 1993)])                              

The items() method returns a list of tuples that contains the primal-value pairs that are inside the lexicon.

How to View All keys Contained in a Lexicon in Python

To see all of the keys that are within a lexicon, apply the built-in keys() method:

                year_of_creation = {'Python': 1993, 'JavaScript': 1995, 'HTML': 1993}  print(year_of_creation.keys())  #output  #dict_keys(['Python', 'JavaScript', 'HTML'])                              

The keys() method returns a list that contains but the keys that are inside the dictionary.

How to View All values Contained in a Lexicon in Python

To see all of the values that are inside a dictionary, utilise the built-in values() method:

                year_of_creation = {'Python': 1993, 'JavaScript': 1995, 'HTML': 1993}  print(year_of_creation.values())  #output  #dict_values([1993, 1995, 1993])                              

The values() method returns a list that contains only the values that are inside the dictionary.

How to Access Private Items in A Dictionary in Python

When working with lists, you access list items by mentioning the list name and using square bracket note. In the foursquare brackets you specify the item'south alphabetize number (or position).

You tin't do exactly the aforementioned with dictionaries.

When working with dictionaries, you can't admission an element by referencing its alphabetize number, since dictionaries comprise fundamental-value pairs.

Instead, you access the detail by using the dictionary proper noun and square bracket note, just this time in the square brackets you specify a cardinal.

Each cardinal corresponds with a specific value, so you mention the key that is associated with the value you want to access.

The full general syntax to practice then is the post-obit:

                dictionary_name[key]                              

Allow's look at the following example on how to admission an item in a Python lexicon:

                my_information = {'proper noun': 'Dionysia', 'age': 28, 'location': 'Athens'}  #access the value associated with the 'historic period' primal print(my_information['age'])  #output  #28                              

What happens though when you endeavor to admission a key that doesn't exist in the dictionary?

                my_information = {'name': 'Dionysia', 'historic period': 28, 'location': 'Athens'}  #try to access the value associated with the 'job' primal impress(my_information['job'])  #output  #line four, in <module> #    print(my_information['chore']) #KeyError: 'chore'                              

It results in a KeyError since there is no such central in the lexicon.

One way to avoid this from happening is to commencement search to see if the key is in the dictionary in the outset place.

You do this past using the in keyword which returns a Boolean value. It returns True if the key is in the dictionary and False if it isn't.

                my_information = {'proper noun': 'Dionysia', 'historic period': 28, 'location': 'Athens'}  #search for the 'job' central print('chore' in my_information)  #output  #False                              

Another way around this is to access items in the dictionary by using the get() method.

You pass the central yous're looking for as an statement and become() returns the value that corresponds with that central.

                my_information = {'name': 'Dionysia', 'age': 28, 'location': 'Athens'}  #try to access the 'job' primal using the get() method impress(my_information.get('job'))  #output  #None                              

As yous detect, when you are searching for a central that does not exist, past default get() returns None instead of a KeyError.

If instead of showing that default None value you lot want to show a different message when a primal does not exist, yous tin can customise get() by providing a unlike value.

You do so by passing the new value as the 2d optional argument to the get() method:

                my_information = {'name': 'Dionysia', 'age': 28, 'location': 'Athens'}  #try to access the 'job' key using the get() method print(my_information.get('chore', 'This value does not exist'))  #output  #This value does not be                              

Now when you are searching for a primal and it is not contained in the dictionary, you will come across the message This value does non exist appear on the console.

How to Modify A Dictionary in Python

Dictionaries are mutable, which ways they are child-bearing.

They can abound and compress throughout the life of the programme.

New items tin exist added, already existing items tin can be updated with new values, and items can be deleted.

How to Add New Items to A Dictionary in Python

To add together a primal-value pair to a dictionary, use foursquare bracket annotation.

The general syntax to do so is the post-obit:

                dictionary_name[key] = value                              

Commencement, specify the proper name of the dictionary. And then, in foursquare brackets, create a key and assign it a value.

Say y'all are starting out with an empty lexicon:

                my_dictionary = {}  print(my_dictionary)  #output  #{}                              

Hither is how you would add a central-value pair to my_dictionary:

                my_dictionary = {}  #add together a central-value pair to the empty dictionary my_dictionary['proper name'] = "John Doe"  #impress dictionary print(my_list)  #output  #{'proper name': 'John Doe'}                              

Here is how you would add some other new key-value pair:

                my_dictionary = {}  #add a key-value pair to the empty dictionary my_dictionary['name'] = "John Doe"  # add another  fundamental-value pair my_dictionary['age'] = 34  #impress dictionary print(my_dictionary)  #output  #{'name': 'John Doe', 'age': 34}                              

Keep in listen that if the key you are trying to add already exists in that dictionary and you are assigning information technology a different value, the cardinal will stop up being updated.

Remember that keys need to be unique.

                my_dictionary = {'name': "John Doe", 'age':34}  print(my_dictionary)  #attempt to create a an 'age' key and assign it a value #the 'age' cardinal already exists  my_dictionary['age'] = 46  #the value of 'age' volition now be updated  impress(my_dictionary)  #output  #{'name': 'John Doe', 'age': 34} #{'proper name': 'John Doe', 'age': 46}                              

If you want to forbid changing the value of an already existing fundamental by blow, you lot might want to check if the fundamental you are trying to add is already in the dictionary.

You practice this by using the in keyword as we discussed to a higher place:

                my_dictionary = {'proper noun': "John Doe", 'age':34}  #I want to add an `age` cardinal. Before I do so, I bank check to see if it already exists print('age' in my_dictionary)  #output  #True                              

How to Update Items in A Dictionary in Python

Updating items in a dictionary works in a like way to adding items to a dictionary.

When you lot know you desire to update one existing fundamental'southward value, use the following general syntax you lot saw in the previous section:

                dictionary_name[existing_key] = new_value                              
                my_dictionary = {'name': "John Doe", 'age':34}  my_dictionary['historic period'] = 46  print(my_dictionary)  #output  #{'proper name': 'John Doe', 'age': 46}                              

To update a lexicon, you can also use the built-in update() method.

This method is particularly helpful when you want to update more than 1 value inside a dictionary at the same time.

Say you lot want to update the name and age key in my_dictionary, and add a new primal, occupation:

                my_dictionary = {'name': "John Doe", 'age':34}  my_dictionary.update(name= 'Mike Greenish', age = 46, occupation = "software developer")  print(my_dictionary)  #output  #{'name': 'Mike Green', 'age': 46, 'occupation': 'software programmer'}                              

The update() method takes a tuple of key-value pairs.

The keys that already existed were updated with the new values that were assigned, and a new key-value pair was added.

The update() method is also useful when you want to add the contents of one dictionary into another.

Say y'all have one dictionary, numbers, and a second dictionary, more_numbers.

If you want to merge the contents of more_numbers with the contents of numbers, apply the update() method.

All the key-value pairs contained in more_numbers will exist added to the end of the numbers dictionary.

                numbers = {'one': one, '2': 2, 'three': three} more_numbers = {'four': four, 'five': five, 'six': half dozen}  #update 'numbers' dictionary #you update it by adding the contents of some other dictionary, 'more_numbers', #to the end of it numbers.update(more_numbers)  impress(numbers)  #output  #{'one': i, 'ii': 2, '3': 3, 'four': iv, 'five': 5, 'six': 6}                              

How to Delete Items from A Dictionary in Python

One of the ways to delete a specific key and its associated value from a dictionary is by using the del keyword.

The syntax to do and so is the following:

                del dictionary_name[key]                              

For example, this is how yous would delete the location key from the my_information dictionary:

                my_information = {'proper noun': 'Dionysia', 'historic period': 28, 'location': 'Athens'}  del my_information['location']  print(my_information)  #output  #{'name': 'Dionysia', 'age': 28}                              

If you lot want to remove a primal, but would likewise like to save that removed value, employ the congenital-in pop() method.

The pop() method removes merely likewise returns the key you specify. This style, y'all can store the removed value in a variable for later utilize or retrieval.

Y'all pass the key y'all want to remove every bit an argument to the method.

Here is the general syntax to do that:

                dictionary_name.pop(key)                              

To remove the location key from the instance above, just this fourth dimension using the pop() method and saving the value associated with the key to a variable, do the post-obit:

                my_information = {'proper noun': 'Dionysia', 'age': 28, 'location': 'Athens'}  urban center = my_information.pop('location')  print(my_information) print(city)  #output  #{'name': 'Dionysia', 'age': 28} #Athens                              

If y'all specify a key that does not exist in the dictionary you will get a KeyError mistake message:

                my_information = {'proper noun': 'Dionysia', 'age': 28, 'location': 'Athens'}  my_information.popular('occupation')  print(my_information)  #output  #line three, in <module> #   my_information.popular('occupation') #KeyError: 'occupation'                              

A way around this is to laissez passer a second argument to the pop() method.

By including the second argument there would exist no mistake. Instead, in that location would exist a silent fail if the fundamental didn't exist, and the dictionary would remain unchanged.

                my_information = {'name': 'Dionysia', 'age': 28, 'location': 'Athens'}  my_information.pop('occupation','Not found')  print(my_information)  #output  #{'name': 'Dionysia', 'historic period': 28, 'location': 'Athens'}                              

The pop() method removes a specific key and its associated value – but what if you only want to delete the terminal key-value pair from a dictionary?

For that, use the congenital-in popitem() method instead.

This is general syntax for the popitem() method:

                dictionary_name.popitem()                              

The popitem() method takes no arguments, but removes and returns the last fundamental-value pair from a dictionary.

                my_information = {'proper noun': 'Dionysia', 'age': 28, 'location': 'Athens'}  popped_item = my_information.popitem()  impress(my_information) print(popped_item)  #output  #{'proper name': 'Dionysia', 'age': 28} #('location', 'Athens')                              

Lastly, if you want to delete all fundamental-value pairs from a dictionary, use the born articulate() method.

                my_information = {'name': 'Dionysia', 'historic period': 28, 'location': 'Athens'}  my_information.clear()  print(my_information)  #output  #{}                              

Using this method will exit you with an empty dictionary.

Determination

And there yous have it! You now know the basics of dictionaries in Python.

I hope you lot constitute this article useful.

To learn more about the Python programming language, cheque out freeCodeCamp's Scientific Computing with Python Certification.

You lot'll start from the nuts and learn in an interacitve and beginner-friendly fashion. You lot'll also build five projects at the cease to put into practice and help reinforce what you lot've learned.

Thanks for reading and happy coding!



Learn to code for free. freeCodeCamp'southward open source curriculum has helped more than 40,000 people become jobs every bit developers. Get started

How To Add Elements To An Empty Dictionary In Python,

Source: https://www.freecodecamp.org/news/create-a-dictionary-in-python-python-dict-methods/

Posted by: barrowsfincureplarl.blogspot.com

0 Response to "How To Add Elements To An Empty Dictionary In Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel