To work with Python dictionary, we should know how to add, delete, update and check the existence of keys. In this article we will look at different methods and calculate their time performance so that you can choose the best alternative for your projects. Let’s start CRUD over Python dictionary.

Methods to create a dictionary

To create empty dictionary –

superhero = {}

Or,

superhero = dict()

To create dictionary with some initial values –

# dictName = {"key1": "value1", "key2": "value2"}

superhero = {
    'avenger1': "Captain America", 
    'avenger2': "Ironman", 
    'avenger3': "Hulk"
}

Or,

# dictName = dict(key1="value1", key2="value2")

superhero = dict(avenger1="Captain America", avenger2="Ironman", avenger3="Hulk")

Or,

# dictName = {k: v for k, v in (('key1', 'value1'), ('key2','value2'))}

superhero = {k: v for k, v in (('avenger1', 'Captain America'), ('avenger2','Ironman'), ('avenger3','Hulk'))}

Methods to add/update keys in dictionary

To add / update single value –

# This will add a new key
# dictName["New Key"] = "Some Value"
superhero["avenger4"] = "Thor"

# This will update the existing key
superhero["avenger2"] = "Hawk Eye"

Or,

# dictName.update({'key': 'value'})

superhero.update({'avenger2': "Hawk Eye"})

Or,

# dictName.update(dict(key='value'))

superhero.update(dict(avenger2="Hawk Eye"))

Or,

# dictName.update(key='value')

superhero.update(avenger2="Hawk Eye")

Or using __setitem__

# dictName.__setitem__(key, 'value')

superhero.__setitem__(avenger2, "Hawk Eye")

To add/update multiple values –

superhero.update({'avenger2': "Hawk Eye", 'avenger5': "Vision"})

Or,

superhero.update(dict(avenger2="Hawk Eye", avenger5="Vision"))

Or,

superhero.update(avenger2="Hawk Eye", avenger5="Vision")

Or by using update operator |,

# dictName = dictName | {"key": "value"}
superhero = superhero | {'avenger2': "Hawk Eye", 'avenger5': "Vision"}

# or

# dictName |= {"key": "value"}
superhero |= {'avenger2': "Hawk Eye", 'avenger5': "Vision"}

Or using feature dictionary unpacking (**) –

# dictName = {**dictName, **{"key": "value"}}

toMergeKeys = {'avenger2': "Hawk Eye", 'avenger5': "Vision"}
superhero = {**superhero, **toMergeKeys}

Methods to delete keys from dictionary

To clear the whole dictionary –

superhero.clear()

To remove key and return the value –

# dictName.pop(key)

whoIsAvenger2 = superhero.pop(avenger2)

To delete a key –

# del dictName[key]

del superhero[avenger2]

Methods to check if key exists in dictionary

# if key in dictName

if avenger2 in superhero:
    return superhero[avenger2]
else:
    return ""

    Tweet this to help others

Time Performance Testing

Let’s check out the time performance of all the methods we have discussed. Then we will select the best one for a particular task.

import timeit
import json

superhero = {};

# Creating EMPTY dictionary

def createEmptyDictionary1():
    superhero = {}

def createEmptyDictionary2():
    superhero = dict()

# Creating NON-EMPTY dictionary

def createNonEmptyDictionary1():
    superhero = {
        'avenger1': "Captain America", 
        'avenger2': "Ironman", 
        'avenger3': "Hulk"
    }

def createNonEmptyDictionary2():
    superhero = dict(avenger1="Captain America", avenger2="Ironman", avenger3="Hulk")

def createNonEmptyDictionary3():
    superhero = {k: v for k, v in (('avenger1', 'Captain America'), ('avenger2','Ironman'), ('avenger3','Hulk'))}


# Add SINGLE value in dictionary

def addSingleValueInDictionary1():
    superhero["avenger4"] = "Thor"

def addSingleValueInDictionary2():
    superhero.update({'avenger2': "Hawk Eye"})

def addSingleValueInDictionary3():
    superhero.update(dict(avenger2="Hawk Eye"))

def addSingleValueInDictionary4():
    superhero.update(avenger2="Hawk Eye")

def addSingleValueInDictionary5():
    superhero.__setitem__("avenger2", "Hawk Eye")


# Add MULTIPLE values in dictionary

def addMultipleValueInDictionary1():
    superhero.update({'avenger2': "Hawk Eye", 'avenger5': "Vision"})

def addMultipleValueInDictionary2():
    superhero.update(dict(avenger2="Hawk Eye", avenger5="Vision"))

def addMultipleValueInDictionary3():
    superhero.update(avenger2="Hawk Eye", avenger5="Vision")

def addMultipleValueInDictionary6():
    global superhero
    toMergeKeys = {'avenger2': "Hawk Eye", 'avenger5': "Vision"}
    superhero = {**superhero, **toMergeKeys}



testFor_CreateEmptyDictionary = {
    '= {}': min(timeit.repeat(lambda: createEmptyDictionary1(), number=100)),
    '= dict()': min(timeit.repeat(lambda: createEmptyDictionary2(), number=100)),
}

testFor_CreateNonEmptyDictionary = {
    '= {key:value}': min(timeit.repeat(lambda: createNonEmptyDictionary1(), number=100)),
    '= dict(key=value)': min(timeit.repeat(lambda: createNonEmptyDictionary2(), number=100)),
    '= {k,v in ((key,value))}': min(timeit.repeat(lambda: createNonEmptyDictionary3(), number=100)),
}

testFor_AddSingleValueInDictionary = {
    'dict[key]=value': min(timeit.repeat(lambda: addSingleValueInDictionary1(), number=100)),
    'dict.update({key:value})': min(timeit.repeat(lambda: addSingleValueInDictionary2(), number=100)),
    'dict.update(dict(key=value))': min(timeit.repeat(lambda: addSingleValueInDictionary3(), number=100)),
    'dict.update(key=value)': min(timeit.repeat(lambda: addSingleValueInDictionary4(), number=100)),
    'dict.__setitem__(key,value)': min(timeit.repeat(lambda: addSingleValueInDictionary5(), number=100)),
}

testFor_AddMultipleValuesInDictionary = {
    'dict.update({key:value, key:value})': min(timeit.repeat(lambda: addMultipleValueInDictionary1(), number=100)),
    'dict.update(dict(key=value, key=value))': min(timeit.repeat(lambda: addMultipleValueInDictionary2(), number=100)),
    'dict.update(key=value, key=value)': min(timeit.repeat(lambda: addMultipleValueInDictionary3(), number=100)),
    '{**dict, **{key:value}}': min(timeit.repeat(lambda: addMultipleValueInDictionary6(), number=100)),
}

print("Benchmarks for Create Empty dictionary")
print(json.dumps(testFor_CreateEmptyDictionary, indent=2))

print("Benchmarks for Create Non-Empty dictionary")
print(json.dumps(testFor_CreateNonEmptyDictionary, indent=2))

print("Benchmarks for Add single value in dictionary")
print(json.dumps(testFor_AddSingleValueInDictionary, indent=2))

print("Benchmarks for Add Multi Value in dictionary")
print(json.dumps(testFor_AddMultipleValuesInDictionary, indent=2))

When I ran the test, I got these benchmarks –

Benchmarks for Create Empty dictionary
{
  "= {}": 2.5695189833641052e-05,
  "= dict()": 5.026068538427353e-05
}
Benchmarks for Create Non-Empty dictionary
{
  "= {key:value}": 3.753695636987686e-05,
  "= dict(key=value)": 6.229616701602936e-05,
  "= {k,v in ((key,value))}": 7.49519094824791e-05
}
Benchmarks for Add single value in dictionary
{
  "dict[key]=value": 3.3933669328689575e-05,
  "dict.update({key:value})": 5.788635462522507e-05,
  "dict.update(dict(key=value))": 7.4826180934906e-05,
  "dict.update(key=value)": 4.909466952085495e-05,
  "dict.__setitem__(key,value)": 4.526413977146149e-05
}
Benchmarks for Add Multi Value in dictionary
{
  "dict.update({key:value, key:value})": 5.984213203191757e-05,
  "dict.update(dict(key=value, key=value))": 8.533988147974014e-05,
  "dict.update(key=value, key=value)": 5.415547639131546e-05,
  "{**dict, **{key:value}}": 5.873199552297592e-05
}

So, here is the verdict –

To create empty dictionary – Use {}

To create non-empty dictionary – Use dictName = {key: value}

To add single value in dictionary – Use dictName[key] = value

To add multi values – Use dictName.update(key1=value1, key2=value2)

Live Demo

Demo might not work in private window (incognito)

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles