Python dictionaries

Share me please

How to create dictionary in Python

[cc lang=”python”]
# creating dictionary
dict1 = {
‘key 1’ : ‘value 1’,
‘key 2’ : ‘value 2’,
‘key 3’ : ‘value 3’
}

print(dict1)
print(type(dict1))

# creating disctionary with build in function dict

dict1 = dict( [
( ‘key 1’, ‘value 1’),
( ‘key 2’, ‘value 2’),
( ‘key 3’, ‘value 3’)
])

print(dict1)
print(type(dict1))
[/cc]

Standard operations with dictionaries

[cc lang=”python”]
# empty dictionary
dict1 = {}
print(dict1)
print(type(dict1))

# add some key->values into dictionary
dict1[‘cat’] = ‘black’
dict1[‘dog’] = ‘brown’
dict1[‘cow’] = ‘white and black’
dict1[‘horse’] = ‘white’
dict1[‘monkey’] = ‘white’

print(dict1)

# delete element by key
del dict1[‘cat’]
print(dict1)
[/cc]

Running functions with python dictionaries

[cc lang=”python” height=”770px”]
# initialize dictionary
dict1 = {
‘key 1’ : ‘value 1’,
‘key 2’ : ‘value 2’,
‘key 3’ : ‘value 3’,
‘key 4’ : ‘value 4’
}

# delete element by key and get a value
dog_color = dict1.pop(‘key 1’)
print(dog_color)
print(dict1)

# get keys from dictionary
print(dict1.keys())
print(type(dict1.keys()))

# get values from dictionary
print(dict1.values())
print(type(dict1.values()))

# get element by value
print(dict1.get(‘key 2’))

# print all items
print(dict1.items())
print(type(dict1.items()))

# delete last item
item = dict1.popitem()
print(item)
print(dict1)

# add one dictionary into another and make update
dict2 = { ‘key 1’ : ‘value 1’, ‘key 2’: ‘value 22222’ }
print(dict2)
print(dict1)
dict1.update(dict2)
print(dict1)

# delete all items
dict1.clear()
print(dict1)
[/cc]

How to convert dictionary to other data types

[cc lang=”python”]
# initilize dictionary
dict1 = { ‘cat’: ‘yellow’, ‘dog’ : ‘black’ }
print(dict1)
print(type(dict1))

# Using zip
listt = zip(dict1.keys(), dict1.values())

# Converting from zip object to list object
listt = list(listt)
print(listt)
print(type(listt))
[/cc]