Changing Dictionary Items in Python: Modifying Key-Value Pairs

thumb_up 1  ·  sell Python dictionary item modification, Modifying key-value pairs in Python dictionaries, Changing dictionary items in Python

Apart from the literal representation of dictionary, where we put comma-separated key:value pairs in curly brackets, we can create dictionary object with built-in dict() function.

Empty Dictionary

Using dict() function without any arguments creates an empty dictionary object. It is equivalent to putting nothing between curly brackets.

Example

 
d1 = dict() d2 = {} print ('d1: ', d1) print ('d2: ', d2)

It will produce the following output −

d1: {}
d2: {}

Dictionary from List of Tuples

The dict() function constructs a dictionary from a list or tuple of two-item tuples. First item in a tuple is treated as key, and the second as its value.

Example

 
d1=dict([('a', 100), ('b', 200)]) d2 = dict((('a', 'one'), ('b', 'two'))) print ('d1: ', d1) print ('d2: ', d2)

It will produce the following output −

d1: {'a': 100, 'b': 200}
d2: {'a': 'one', 'b': 'two'}

Dictionary from Keyword Arguments

The dict() function can take any number of keyword arguments with name=value pairs. It returns a dictionary object with the name as key and associates it to the value.

Example

 
d1=dict(a= 100, b=200) d2 = dict(a='one', b='two') print ('d1: ', d1) print ('d2: ', d2)

It will produce the following output −

d1: {'a': 100, 'b': 200}
d2: {'a': 'one', 'b': 'two'}


The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.

Was this answer helpful?

Related Articles

description

Exploring Python's Key Characteristic

Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language. This tutorial will list down some of…

arrow_forward
description

Comparing Python and C++

Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this…

arrow_forward
description

Creating a Python Hello World Program

This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of…

arrow_forward
description

Python's Versatile Application Domains

Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few…

arrow_forward
description

Understanding the Python Interpreter

Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the…

arrow_forward
arrow_back « Back