Adding elements to dictionary python

Add a new item to a dictionary in Python [duplicate]

@GlabbichRulz: your solution is exactly the elegant approach I was hoping to find here — would you care to turn your comment into an answer so I can upvote it ? would also get me a direct link I can save for future reference.

3 Answers 3

Another possible solution:

which is nice if you want to insert multiple items at once.

Sorry for the thread necro, but is there any reason to prefer one method over the other when adding one item?

@Warrick there’s absolutely no difference except for personal taste. Personally I find the first to be a little more intuitive for just one item.

@user3067923 This is pure conjecture but I imagine that the first one would be marginally faster since it’s mutating the dict in place, whereas the second one has to create a temporary dict, then mutate, then garbage collect the temporary dict. I’d need to benchmark it to say definitively.

Читайте также:  Netscape to json javascript

As Chris’ answer says, you can use update to add more than one item. An example:

It occurred to me that you may have actually be asking how to implement the + operator for dictionaries, the following seems to work:

>>> class Dict(dict): . def __add__(self, other): . copy = self.copy() . copy.update(other) . return copy . def __radd__(self, other): . copy = other.copy() . copy.update(self) . return copy . >>> default_data = Dict() >>> default_data +  >>> + Dict(test2=2)

Note that this is more overhead then using dictAdding elements to dictionary python = value or dict.update() , so I would recommend against using this solution unless you intend to create a new dictionary anyway.

Источник

Python Add to Dictionary – Adding an Item to a Dict

Ihechikara Vincent Abba

Ihechikara Vincent Abba

Python Add to Dictionary – Adding an Item to a Dict

Data structures help us organize and store collections of data. Python has built-in data structures like Lists, Sets, Tuples and Dictionaries.

Each of these structures have their own syntax and methods for interacting with the data stored.

In this article, we’ll talk about Dictionaries, their features, and how to add items to them.

How to Create a Dictionary in Python

Dictionaries are made up of key and value pairs nested in curly brackets. Here’s an example of a Dictionary:

In the code above, we created a dictionary called devBio with information about a developer – the developer’s age is quite overwhelming.

Each key in the dictionary – name , age and language – has a corresponding value. A comma separates each key and value pair from another. Omitting the comma throws an error your way.

Before we dive into how we can add items to our dictionaries, let’s have a look at some of the features of a dictionary. This will help you easily distinguish them from other data structures in Python.

Features of a Dictionary

Here are some of the features of a dictionary in Python:

Duplicate Keys Are Not Allowed

If we create a dictionary that has two or multiple identical keys in it, the last key out of them will override the rest. Here’s an example:

We created three keys with an identical key name of name . When we printed our dictionary to the console, the last key having a value of «Chikara» overwrote the rest.

Let’s see the next feature.

Items in a Dictionary Are Changeable

After assigning an item to a dictionary, you can change its value to something different.

devBio = < "name": "Ihechikara", "age": 120, "language": "JavaScript" >devBio["age"] = 1 print(devBio) #

In the example above, we reassigned a new value to age . This will override the initial value we assigned when the dictionary was created.

We can also use the update() method to change the value of items in our dictionary. We can achieve the same result in the last example by using the update() method – that is: devBio.update() .

Items in a Dictionary Are Ordered

By being ordered, this means that the items in a dictionary maintain the order in which they were created or added. That order cannot change.

Prior to Python 3.7, dictionaries in Python were unordered.

In the next section, we will see how we can add items to a dictionary.

How to Add an Item to a Dictionary

The syntax for adding items to a dictionary is the same as the syntax we used when updating an item. The only difference here is that the index key will include the name of the new key to be created and its corresponding value.

Here’s what the syntax looks like: devBio[newKey] = newValue .

We can also use the update() method to add new items to a dictionary. Here’s what that would look like: devBio.update(newKey«: newValue>) .

devBio = < "name": "Ihechikara", "age": 120, "language": "JavaScript" >devBio["role"] = "Developer" print(devBio) #

Above, using the index key devBio[«role»] , we created a new key with the value of Developer .

In the next example, we will use the update() method.

devBio = < "name": "Ihechikara", "age": 120, "language": "JavaScript" >devBio.update() print(devBio) #

Above, we achieved the same result as in the last example by passing in the new key and its value into the update() method – that is: devBio.update() .

Conclusion

In this article, we learned what dictionaries are in Python, how to create them, and some of their features. We then saw two ways through which we can add items to our dictionaries.

Источник

Как добавить элемент в словарь

Перед тем как начинать, попробуйте решить задачку по словарям, чтобы освежить знания, или пропустите этот блок.

Словари — структура данных. Внутри нее хранятся элементы по принципу «ключ-значение».

При работе со словарями у вас, возможно, возникал вопрос — а как добавить элемент в словарь. В этой статье вы найдете ответ.

Также мы поговорим об основах, о том, как словари работают. И конечно же, разберем, как добавить элемент в словарь. К концу статьи вы станете экспертом в этом деле!

Словари. Краткое введение

Структура словаря позволяет вам привязывать ключи к значениям. Это довольно полезно — можно использовать ключ как ярлык. То есть, если вы хотите получить доступ к какому-то значению, вам нужно просто указать соответствующий ключ.

Словари обычно используются для данных, которые связаны друг с другом. Например, журнал посещаемости студента или цвета ковров, которые вы бы хотели купить.

Словарь выглядит следующим образом:

В этом словаре содержится четыре ключа и четыре значения. Ключи хранятся в виде строки и находятся в левом столбце. Значения же хранятся в правом столбце и привязаны к соответствующим ключам.

И все же — как добавить элемент в словарь? Давайте разберемся.

Как добавить элемент в словарь

Чтобы добавить элемент в словарь, вам нужно привязать значение к новому ключу.

В отличие от списков и кортежей, в работе со словарями методы add() , insert() и append() вам не помощники. Тут необходимо создать новый ключ. Позже он будет использоваться для хранения значения.

Добавляются элементы в словарь так:

dictionary_nameAdding elements to dictionary python = value

Рассмотрим пример, чтобы разобраться. В нашем словаре было четыре пары ключ-значение. Этот словарь отражает количество булочек, которые продаются в кафе.

Допустим, мы испекли 10 вишневых булочек. Теперь нам нужно внести их в словарь. Сделать это можно так:

scones = < "Фрукты": 22, "Пустая": 14, "Корица": 4, "Сыр": 21 >scones["Вишня"] = 10 print(scones)

Как видите, мы добавили в словарь ключ Вишня и присвоили ему значение 10.

Сперва мы объявили словарь scones , хранящий информацию о булочках, которые доступны к заказу в нашем кафе. Потом мы добавили в наш словарь ключ Вишня и присвоили ему значение 10:

И, наконец, мы вывели в консоль обновленную версию словаря.

Заметьте, что в выводе наш словарь не упорядочен. Это происходит из-за того, что данные, хранящиеся в словаре, в отличие от списка, не упорядочены.

Совет: добавление и обновление происходит одинаково

Тем же способом мы можем обновить значение ключа. Допустим, мы испекли еще 10 булочек с корицей. Обновить значение этого ключа можно так:

scones = < "Фрукты": 22, "Пустая": 14, "Корица": 4, "Сыр": 21 >scones["Корица"] = 14 print(scones)

То есть, тем же способом мы можем установить новое значение какому-либо ключу. В нашем случае мы присвоили Корица значение 14.

Источник

Python: How to Add Items to Dictionary

Dictionaries are Python’s built-in data types for storing key-value pairs. The dictionary elements are changeable and don’t allow duplicates. In Python 3.7 and higher, dictionary items are ordered. Lower versions of Python treat dictionary elements as unordered.

Depending on the desired result and given data, there are various ways to add items to a dictionary.

This guide shows how to add items to a Python dictionary through examples.

Python: How To Add Items To A Dictionary

  • Python version 3.7 or higher.
  • A text editor or IDE to write code.
  • A method to run the code, such as a terminal or IDE.

How to Add an Item to a Dictionary in Python

To test out different methods of adding items to a dictionary, create a dictionary with two items. Use the following code:

The methods below show how to add one or multiple items to a Python dictionary.

Note: Adding an item with an existing key replaces the dictionary item with a new value. Make sure to provide unique keys to avoid overwriting data.

Method 1: Using The Assignment Operator

The assignment operator sets a value to a key using the following syntax:

dictionary_nameAdding elements to dictionary python = value

The assignment operator adds a new key-value pair if the key does not exist.

The following code demonstrates how to add an item to a Python dictionary using the assignment operator:

my_dictionary = < "one": 1, "two": 2 >print("Before:", my_dictionary) my_dictionary["tree"] = 3 print("After:", my_dictionary)

Python add item to dictionary assignment

The code outputs the dictionary contents before and after adding a new item.

Method 2: Using update()

The update() method updates an existing dictionary with a new dictionary item:

The method accepts one or multiple key-value pairs, which is convenient for adding more than one element.

The example code looks like the following:

my_dictionary = < "one": 1, "two": 2 >print("Before:", my_dictionary) my_dictionary.update() print("After:", my_dictionary)

Python add item to dictionary update method

Use this method to add multiple new items or append a dictionary to an existing one.

Method 3: Using __setitem__

The __setitem__ method is another way to append a new dictionary item:

dictionary_name.__setitem__(key,value)
my_dictionary = < "one": 1, "two": 2 >print("Before:", my_dictionary) my_dictionary.__setitem__("three", 3) print("After:", my_dictionary)

Python add item to dictionary setitem method

The method sets the item key as «three» with the value 3 .

Method 4: Using The ** Operator

The ** operator helps merge an existing dictionary into a new dictionary and adds additional items. The syntax is:

For example, to copy an existing dictionary and append a new item to a new one, see the following code:

my_dictionary = < "one": 1, "two": 2 >my_new_dictionary = <**my_dictionary, **<"three":3>> print("Old:", my_dictionary) print("New:", my_new_dictionary)

Python add item to dictionary copy

The new dictionary contains the added item, preserving the old dictionary values. Use this method to avoid changing existing dictionaries.

Method 5: Checking If A Key Exists

Use an if statement to check whether a key exists before adding a new item to a dictionary. The example syntax is:

if key not in dictionary_name: dictionary_nameAdding elements to dictionary python = value
my_dictionary = < "one": 1, "two": 2 >print("Before:", my_dictionary) if "three" not in my_dictionary: my_dictionary["three"] = 3 print("After:", my_dictionary)

Python add item to dictionary if not in statement

The code checks whether a key with the provided name exists before adding the item to the dictionary. If the provided key exists, the existing key value does not update, and the dictionary stays unchanged.

Method 6: Using A For Loop

Add key-value pairs to a nested list and loop through the list to add multiple items to a dictionary. For example:

my_dictionary = < "one": 1, "two": 2 >my_list = [["three", 3], ["four", 4]] print("Before:", my_dictionary) for key,value in my_list: my_dictionaryAdding elements to dictionary python = value print("After:", my_dictionary)

Python add item to dictionary nested list

The for loop goes through the pairs inside the list and adds two new elements.

Note: For loop and a counter are also used as one of the methods to identify the length of a list. Learn more by visiting our guide How to Find the List Length in Python.

Method 7: Using zip

Use zip to create key-value pairs from two lists. The first list contains keys and the second contains the values.

my_dictionary = < "one": 1, "two": 2 >my_keys = ["three", "four"] my_values = [3, 4] print("Before:", my_dictionary) for key,value in zip(my_keys, my_values): my_dictionaryAdding elements to dictionary python = value print("After:", my_dictionary)

Python add item to dictionary zip

The zip function matches elements from two lists by index, creating key-value pairs.

How to Update a Python Dictionary

Update Python dictionary values using the same syntax as adding a new element. Provide the key name of an existing key, for example:

my_dictionary = < "one": 1, "two": 2 >print("Before:", my_dictionary) my_dictionary["one"] = 3 print("After:", my_dictionary)

Since Python does not allow duplicate entries in a dictionary, the code updates the value for the provided key and overwrites the existing information.

After going through the examples in this tutorial, you know how to add items to a Python dictionary. All methods provide unique functionalities, so choose a way that best suits your program and situation.

For more Python tutorial refer to our article and find out how to pretty print a JSON file using Python.

Источник

Оцените статью