Wednesday, May 22, 2019

Python Dictionary

Links: Journey to Data Scientist


Characteristics
  • Unordered (followed the sequence the keys were added)
  • Mutable
  • Can be nested
  • Access via key

#create an empty dictionary
d = {}
print(type(d))

Output: <class 'dict'>


d = {'key1':'value1',2:'value2',0.01:201}
print(d)
print(d['key1'])
print(d[2])
print(d[0.01])

Output:
{'key1': 'value1', 2: 'value2', 0.01: 201}
value1
value2
201


d[2] = 'update value'
print(d[2])

Output: update value


for k, v in d.items():
  print(k, ":", v)

Output:
key1 : value1
2 : update value
0.01 : 201


if 'key1' in d:
  print(d['key1'])

Output: value1


d['add'] = 1990
print(d)

Output: {'key1': 'value1', 2: 'update value', 0.01: 201, 'add': 1990}


d.pop('add')
print(d)

Output: {'key1': 'value1', 2: 'update value', 0.01: 201}


print(d)
d.clear()
print(d)

Output:
{'key1': 'value1', 2: 'value2', 0.01: 201}
{}


No comments: