Python >> Tips and Tricks 2

2022-08-13 Python

Table of Contents

This tutorial will explain how to add elements to list, add element to dictionary, access element in list, access element in dictionary.

Python

Python How to add element to a list

Use append() method

# Use append() method
mylist = [1,2,3]
mylist.append(4)
print(mylist)

[1, 2, 3, 4]

Use insert() method

# Use insert() method
mylist = [1,2,3]
mylist.insert(0,0)
print(mylist)

[0, 1, 2, 3]

Use extend() method

# Use extend() method
mylist = [1,2,3]
mylist.extend([4,5,6])
print(mylist)

[1, 2, 3, 4, 5, 6]

Use + operator to add two lists

# Use + operator to add two lists
mylist = [1,2,3]
mylist2 = [4,5,6]
mylist3 = mylist + mylist2
print(mylist3)

[1, 2, 3, 4, 5, 6]

Use * operator to add list to another list

# Use * operator to add list to another list
mylist = [1,2,3]
mylist2 = mylist * 3
print(mylist2)

[1, 2, 3, 1, 2, 3, 1, 2, 3]

Python How to add element to a dictionary

Use “=” assignment operator

# Use "=" assignment operator to add element to a dictionary
mydict = {"a":1, "b":2, "c":3}

mydict["d"] = 4
print(mydict)

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Use setdefault() method

# Use setdefault() method
mydict = {'a':1, 'b':2, 'c':3}
mydict.setdefault('d', 4)

print(mydict)

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Use update() method

# Use update() method
mydict = {'a':1, 'b':2, 'c':3}
mydict.update({"d":4})

print(mydict)

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Use ** operator to add dictionary to another dictionary


# Use ** operator to add dictionary to another dictionary
mydict = {"a":1, "b":2, "c":3}
mydict2 = {"d":4}
mydict3 = {**mydict, **mydict2}

print(mydict3)

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Use the | operator to add dictionary to another dictionary

# Use the | operator to add dictionary to another dictionary
mydict = {"a":1, "b":2, "c":3}
mydict2 = {"d":4}
mydict3 = mydict | mydict2

print(mydict3)

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Use collections.ChainMap() to add dictionary to another dictionary

# Use collections.ChainMap() to add dictionary to another dictionary
from collections import ChainMap

mydict = {"a":1, "b":2, "c":3}
mydict2 = {"d":4}
mydict3 = ChainMap(mydict, mydict2)

print(mydict3)

ChainMap({'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'d': 4})

Python how to access dictionary

Use square bracket operator to get value

# Use square bracket operator
mydict = {"a":1, "b":2, "c":3}

print(mydict["a"])
# KeyError will occur if the key is not found
print(mydict["d"])
1
KeyError                                  Traceback (most recent call last)
Untitled-1.ipynb Cell 29 in <cell line: 5>()
      2 mydict = {"a":1, "b":2, "c":3}
      4 print(mydict["a"])
----> 5 print(mydict["d"])

KeyError: 'd'

Use get() method to get value

# Use get() method
mydict = {"a":1, "b":2, "c":3}

print(mydict.get("a"))
# None will be returned if the key is not found
print(mydict.get("d"))
1
None

Check if a key is in a dictionary

# Use in operator
mydict = {"a":1, "b":2, "c":3}

if "a" in mydict:
    print("a is in mydict")
else:
    print("a is not in mydict")
a is in mydict

Get all keys of a dictionary

# Use keys() method
mydict = {"a":1, "b":2, "c":3}

print(list(mydict.keys()))
['a', 'b', 'c']

Get all values of a dictionary

# Use values() method
mydict = {"a":1, "b":2, "c":3}

print(list(mydict.values()))
[1, 2, 3]

Get all items of a dictionary

# Use items() method
mydict = {"a":1, "b":2, "c":3}

print(list(mydict.items()))
[('a', 1), ('b', 2), ('c', 3)]

Loop through all keys and values of a dictionary

# Loop through all keys and values of a dictionary
mydict = {"a":1, "b":2, "c":3}

for key, value in mydict.items():
    print(key, value)
a 1
b 2
c 3

Python how to access list

Use square bracket operator to get value

# Use square bracket operator
mylist = [1,2,3]

print(mylist[0])
# IndexError will occur if the index is out of range
print(mylist[3])

Python Tips and Tricks

Get last element of a list

# Use -1 index to get last element of a list
mylist = [1,2,3]

print(mylist[-1])
3

Get part of a list

# Use slice operator to get part of a list
mylist = [1,2,3,4,5,6,7,8,9,10]

print(mylist[0:5])
print(mylist[5:])
print(mylist[:5])
print(mylist[:])
[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Loop through all elements of a list

# Loop through all elements of a list
mylist = [1,2,3]

for element in mylist:
    print(element)
1
2
3

Subscribe and be the FIRST reader of our latest articles

* indicates required

Contact us