Skip to content

Instantly share code, notes, and snippets.

@pknowledge
Created September 3, 2018 16:39
Show Gist options
  • Save pknowledge/8ad5eaab1e22d972131c24b0c2bd7c8e to your computer and use it in GitHub Desktop.
Save pknowledge/8ad5eaab1e22d972131c24b0c2bd7c8e to your computer and use it in GitHub Desktop.
Python Dictionaries
>>> D = {'name': 'max', 'age': 14, 'year': 2004}
>>> D
{'name': 'max', 'year': 2004, 'age': 14}
>>> D['name']
'max'
>>> D['age']
14
>>> E = {'name':'Tom', 15: 15, 15.1:15.1, True: True, (2,3): 5}
>>> E[(2,3)]
5
>>> E[True]
True
>>> E[15]
15
>>> E[100]
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 100
>>> len(E)
5
>>> D.get('name')
'max'
>>> D
{'name': 'max', 'year': 2004, 'age': 14}
>>> D['Surname'] = 'Tesar'
>>> D
{'name': 'max', 'year': 2004, 'Surname': 'Tesar', 'age': 14}
>>> D.pop('Surname')
'Tesar'
>>> D
{'name': 'max', 'year': 2004, 'age': 14}
>>> E
{True: True, 'name': 'Tom', 15.1: 15.1, (2, 3): 5, 15: 15}
>>> E.clear()
>>> E
{}
>>> del E
>>> E
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'E' is not defined
>>> D
{'name': 'max', 'year': 2004, 'age': 14}
>>> D['name'] = 'tom'
>>> D
{'name': 'tom', 'year': 2004, 'age': 14}
>>> D.update({'name': 'max'})
>>> D
{'name': 'max', 'year': 2004, 'age': 14}
>>> D.keys()
dict_keys(['name', 'year', 'age'])
>>> D.values()
dict_values(['max', 2004, 14])
>>> D.items()
dict_items([('name', 'max'), ('year', 2004), ('age', 14)])
>>> D
{'name': 'max', 'year': 2004, 'age': 14}
>>> D.popitem()
('name', 'max')
>>> D
{'year': 2004, 'age': 14}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment