Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Writing a dictionary in this form (single or multiple lines)
- # allows keys to be either an integer or a string
- dictionary = {
- 1: 'value 1',
- 2: 'value 2',
- 3: 'value 3',
- }
- print(dictionary)
- # {'key 1': 'value 1', 'key 2': 'value 2', 'key 3': 'value 3'}
- print(dictionary[1])
- # value 1
- dictionary = {
- 'key 1': 'value 1',
- 'key 2': 'value 2',
- 'key 3': 'value 3',
- }
- print(dictionary)
- # {'key 1': 'value 1', 'key 2': 'value 2', 'key 3': 'value 3'}
- print(dictionary['key 2'])
- # value 2
- # Alternatively
- # When we write dictionary in this form below keys can't
- # be integers (as compared to the first example)
- # change key1, key2, key3 to 1, 2, 3 respectively
- # When keys are integers, 'SyntaxError: keyword can't be
- # an expression' is prompted in the console.
- # This means keys can only be a set of alphabet or alphanumeric name or
- # key which is converted to a string.
- dictionary = dict(key1='value 1', key2='value 2', key3='value 3')
- print(dictionary)
- # {'key1': 'value 1', 'key2': 'value 2', 'key3': 'value 3'}
- print(dictionary['key2'])
- # value 2
- dictionary = dict(name='Osagie', age=25, country='Nigeria')
- print(dictionary)
- # {'name': 'Osagie', 'age': 25, 'country': 'Nigeria'}
- print(dictionary['name'])
- # Osagie
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement