Cara menggunakan python concatenate dict keys

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

In Python, a dictionary is a data structure that contains elements in the form of a key-value pair where keys are used to access the values of the dictionary. Python dictionaries are unordered and mutable i.e. the elements of the dictionaries can be changed.

In this article, we will explore five different ways to merge two or more dictionaries, along with a crude way.

For this article, let us create two dictionaries

d3 = d1.copy()
for key, value in d2.items():
d3[key] = value

print(d3)
8 and
d3 = d1.copy()
for key, value in d2.items():
d3[key] = value

print(d3)
9 which we want to concatenate into a single dictionary:

d1 = {'India': 'Delhi',
'Canada': 'Ottawa',
'United States': 'Washington D. C.'}

d2 = {'France': 'Paris',
'Malaysia': 'Kuala Lumpur'}

The Crude Way

You can merge two dictionaries by iterating over the key-value pairs of the second dictionary with the first one.

d3 = d1.copy()
for key, value in d2.items():
d3[key] = value

print(d3)
Output:

{'India': 'Delhi',
'Canada': 'Ottawa',
'United States': 'Washington D. C.',
'France': 'Paris',
'Malaysia': 'Kuala Lumpur'}

Now, let us see cleaner and better ways of merging the dictionaries:

Method 1: Using the update method

Dictionary has a method which merges the dictionary with the items from the other dictionary in place and overwrites existing keys.

d4 = d1.copy()
d4.update(d2)

print(d4)
Output:
{'India': 'Delhi',
'Canada': 'Ottawa',
'United States': 'Washington D. C.',
'France': 'Paris',
'Malaysia': 'Kuala Lumpur'}

The update method modifies the current dictionary. So you might want to create a copy of the dictionary before operating on the dictionary.

Method 2: Using the unpacking operator

We can merge dictionaries in one line by simply using the unpacking operator (**).

d5 = {**d1, **d2}

print(d5)
Output:
{'India': 'Delhi',
'Canada': 'Ottawa',
'United States': 'Washington D. C.',
'France': 'Paris',
'Malaysia': 'Kuala Lumpur'}

We can also merge multiple dictionaries using this method.

{**dict1, **dict2, **dict3}

Method 3: Using collections.ChainMap

This is, perhaps, the least known method to merge dictionaries.
class from the Collections module groups multiple dictionaries in a single view.

from collections import ChainMap
d6 = ChainMap(d1, d2)

print(d6)
Output:
ChainMap({'Canada': 'Ottawa',
'India': 'Delhi',
'United States': 'Washington D. C.'},
{'France': 'Paris',
'Malaysia': 'Kuala Lumpur'})

This method returns an object of the ChainMap class. We can, still, use this object as we would use any other dictionary. e.g.

Output:

{'India': 'Delhi',
'Canada': 'Ottawa',
'United States': 'Washington D. C.',
'France': 'Paris',
'Malaysia': 'Kuala Lumpur'}
0 will return
Output:

{'India': 'Delhi',
'Canada': 'Ottawa',
'United States': 'Washington D. C.',
'France': 'Paris',
'Malaysia': 'Kuala Lumpur'}
1.

However, in the case of the same keys in two dictionaries, this method will return the value of the first dictionary, unlike the other methods which return the value from the second dictionary.

Dictionary Python berbeda dengan List ataupun Tuple. Karena setiap urutanya berisi key dan value. Setiap key dipisahkan dari value-nya oleh titik dua (:), item dipisahkan oleh koma, dan semuanya tertutup dalam kurung kurawal. Dictionary kosong tanpa barang ditulis hanya dengan dua kurung kurawal, seperti ini: {}.

Nilai kamus bisa berupa tipe apa pun, namun key harus berupa tipe data yang tidak berubah seperti string, angka, atau tupel.

Akses Nilai Dalam Dictionary Python

Untuk mengakses elemen Dictionary, Anda dapat menggunakan tanda kurung siku yang sudah dikenal bersama dengan key untuk mendapatkan nilainya. Berikut adalah contoh sederhananya :

#Contoh cara membuat Dictionary pada Python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])

Anda dapat memperbarui Dictionary dengan menambahkan entri baru atau pasangan nilai kunci, memodifikasi entri yang ada, atau menghapus entri yang ada seperti ditunjukkan pada contoh sederhana yang diberikan di bawah ini.

#Update dictionary python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # Mengubah entri yang sudah ada
dict['School'] = "DPS School" # Menambah entri baru

print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

Hapus Elemen Dictionary Python

Anda dapat menghapus elemen Dictionary individual atau menghapus keseluruhan isi Dictionary. Anda juga dapat menghapus seluruh Dictionary dalam satu operasi.

Untuk menghapus seluruh Dictionary secara eksplisit, cukup gunakan del statement. Berikut adalah contoh sederhana :