Adding values to dict in python

How to add key,value pair to dictionary? [duplicate]

Thanks it’s working..I meant resultset of query. Do you know which are the concerns using python..i don’t know am new of this technology before i have worked in dotnet.

@Krishnasamy: If you have earlier worked on dotnet, Python will be a pleasure to work with. It is as versatile as dotnet and java, if not more

For quick reference, all the following methods will add a new key ‘a’ if it does not exist already or it will update the existing key value pair with the new value offered:

data['a']=1 data.update() data.update(dict(a=1)) data.update(a=1) 

You can also mixing them up, for example, if key ‘c’ is in data but ‘d’ is not, the following method will updates ‘c’ and adds ‘d’

Why is the down vote? The answer is trying to add useful info so viewers can have an alternative answer which IMHO is more comprehensive, could the gentleman/women who down voted pls clarify?

You don’t need to answer this question since its a duplicate — the appropriate way of handling it is by flagging it as a dupe — see more info there How should duplicate questions be handled?

SO really needs to figure out a way to make things surface better. This is down voted for being a duplicate. But it’s the first thing that appears when a user searches. The down vote then starts more conversation, which causes this answer to FURTHER rise in popularity, thereby hiding the original answer. I would have never have found the original answer had this one not existed. So why not just delete this qeustion completely?

I am not sure what you mean by «dynamic». If you mean adding items to a dictionary at runtime, it is as easy as dictionaryAdding values to dict in python = value .

If you wish to create a dictionary with key,value to start with (at compile time) then use (surprise!)

I got here looking for a way to add a key/value pair(s) as a group — in my case it was the output of a function call, so adding the pair using dictionaryAdding values to dict in python = value would require me to know the name of the key(s).

Читайте также:  Rest assured java maven

In this case, you can use the update method: dictionary.update(function_that_returns_a_dict(*args, **kwargs)))

Beware, if dictionary already contains one of the keys, the original value will be overwritten.

Источник

Python Dictionary Append: How to add key-value pair

In this Python tutorial, we will learn about the Python dictionary append. Here appending to Python Dictionary means adding new key-value pair to a Python Dictionary.

In Python, we can append data into the Python DIctionary using the following 6 methods.

  1. Using append() method
  2. Using dict.update() method
  3. Using extend() method
  4. Using for loop
  5. Using square brackets
  6. Using dictionary comprehension
  7. Using dict() constructor

Python Dictionary Append

Here, the basic meaning of the Pyhton Dictionary Append is to add new key-value pair to an existing Python Dictionary.

And we can easily append a key-value pair into a dictionary in Python using multiple methods. So, let us start with the first method:

Method 1: Python Dictionary Append using dict() constructor

In Python, we can also define a dictionary and its objects using the dict() constructor. Moreover, we can use the same dict() function on an existing dictionary to add more key-value pairs to the dictionary.

Here is an example of the implementation.

# Defining a dictionary in Python countries_hdi = < 'Canada': 0.937, 'United Kingdom': 0.935, 'United States': 0.921, >print("Original Dictionary:", countries_hdi) # Using dict() to append data countries_hdi = dict(countries_hdi, Australia=0.941) print("Dictionary after adding data:", countries_hdi)

In the example, we append the ley-value pair to the countries_hdi dictionary.

So, after executing the above Python program, we will get the following result.

Original Dictionary: Dictionary after adding data: 'Australia': 0.941>

So, in this section, we understood how to add key-value pairs to the dictionary using dict() constructor in Python.

Method 2: Python Dictionary Append using dictionary comprehension

With this method, we will understand how to use the unpacking operator (**) with dictionary comprehension to append new key-value pair to an existing dictionary.

The Python code for this execution is given below.

# Defining a dictionary in Python countries_hdi = < 'Canada': 0.937, 'United Kingdom': 0.935, 'United States': 0.921, >print("Original Dictionary:", countries_hdi) # Using dict comprehension to append data countries_hdi = <**countries_hdi, **<'Switzerland': 0.962>> print("Dictionary after adding data:", countries_hdi)

Here we used the unpacking operator with dictionary comprehension to append key-value pair to countries_hdi dictionary.

Once we run the above Python program, we will get the following result.

Original Dictionary: Dictionary after adding data: 'Switzerland': 0.962>

So, in this section, we understood how to add key-value pairs to the dictionary using dictionary comprehension and the unpacking operator (**) in Python.

Method 3: Python Dictionary Append using square brackets

One of the simplest methods to append or add new key-value pair to an existing Python Dictionary is by using the square brackets.

Basically, the square brackets are used with a dictionary to fetch the value of an existing key. However, if a particular key does not exist, it will add automatically.

# Defining a dictionary in Python countries_hdi = < 'Canada': 0.937, 'United Kingdom': 0.935, 'United States': 0.921, >print("Original Dictionary:", countries_hdi) # Using square brackets to append key-value pair countries_hdi['Australia'] = 0.941 countries_hdi['Switzerland'] = 0.962 print("Dictionary after adding data:", countries_hdi)

In the above example, we are using square brackets to append new values for Australia and Switzerland keys.

The result of the above Python program is shown below.

Original Dictionary: Dictionary after adding data: 'Australia': 0.941, 'Switzerland': 0.962>

So, in this section, we understood how to add or append key-value pairs to the dictionary using square brackets in Python.

Method 4: Python Dictionary Append using for loop

Now, if we use square brackets, we need to specify each key-value pair manually. However, we can simplify this approach by creating a list containing key-value tuples.

After this, we will use the for loop and square brackets to iterate over each key-value pair and append it to the existing Python dictionary.

# Defining a dictionary in Python countries_hdi = < 'Canada': 0.937, 'United Kingdom': 0.935, 'United States': 0.921, >print("Original Dictionary:", countries_hdi) # Defining new key-value pairs new_items = [('Australia', 0.941), ('Switzerland', 0.962)] # Using for loop to append key-value pair for key, value in new_items: countries_hdiAdding values to dict in python = value print("Dictionary after adding data:", countries_hdi)

Once we execute the above Python program, we will get the following result.

Original Dictionary: Dictionary after adding data: 'Australia': 0.941, 'Switzerland': 0.962>

In this section, we understood how to add or append key-value pairs to the dictionary using for loop and square brackets in Python.

Method 5: Python Dictionary Append using dict.update()

The dict.update() is a built-in dictionary method in Python that allows to add new values to an existing dictionary.

Here is an example of using the dict.update() to add key-value pairs to an existing Python dictionary.

# Defining a dictionary in Python countries_hdi = < 'Canada': 0.937, 'United Kingdom': 0.935, 'United States': 0.921, >print("Original Dictionary:", countries_hdi) # Appending key-value using update() method countries_hdi.update() print("Dictionary after appending data:", countries_hdi)

In the example, we are appending the key-value pair to the countries_hdi dictionary.

Original Dictionary: Dictionary after appending data: 'Switzerland': 0.962>

In this section, we understood how to add or append key-value pairs to the dictionary using dict.update() in Python.

Method 6: Python Dictionary Append using append() method

Till now, we were focusing only on appending key-value pairs to an existing dictionary. However, here we will see how to append more values to an existing key in the Python Dictionary.

For this, we can use the append() method in Python.

The append() is a built-in list method in Python that allows appending more values to an existing list. If in a dictionary, a key holds a list of values, we can use the append() method to append more values to the list.

# Defining a dictionary in Python user_data = < 'Name': 'Alex', 'Age': 32, 'City': 'Chicago', 'Country': 'United States', 'Technical Skills': ['SQL', 'Java'] >print("Original Dictionary:", user_data) # Using append() method to append elements to list user_data['Technical Skills'].append('Python') user_data['Technical Skills'].append('Salesforce') print("Dictionary after appending data:", user_data)

Once we execute the python program, we will get the following result.

Python Dictionary Append Example

At the end of this section, we understood to append values to an existing Python DIctionary Key using append().

Method 7: Python Dictionary Append using extend() method

In the previous example, we have seen how to append new values to an existing key in Python Dictionary. However, by using the above approach, we have to manually append each element to a dictionary key.

So, to overcome this issue, we can use the extend() method in Python. The extend() is a built-in list method that allows appending multiple values to a list.

Here we have illustrated the example of using the extend() method in Python.

# Defining a dictionary in Python user_data = < 'Name': 'Alex', 'Age': 32, 'City': 'Chicago', 'Country': 'United States', 'Technical Skills': ['SQL', 'Java'] >print("Original Dictionary:", user_data) # Using extend() method to append elements to list user_data['Technical Skills'].extend(['Python', 'Salesforce']) print("Dictionary after appending data:", user_data)

In the above example, we appended 2 values to the Technical Skills key in the user_data dictionary.

Python Dictionary Append

In this section, we understood to append values to an existing Python DIctionary Key using extend().

You may also like to read the following Python tutorials.

Conclusion

At the end of this Python tutorial, we understood how to append key-value pairs to an existing Python Dictionary. Moreover, we have illustrated the following 7 methods for Python Dictionary Append.

  1. Using append() method
  2. Using dict.update() method
  3. Using extend() method
  4. Using for loop
  5. Using square brackets
  6. Using dictionary comprehension
  7. Using dict() constructor

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

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