Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. # Writing a dictionary in this form (single or multiple lines)
  2. # allows keys to be either an integer or a string
  3. dictionary = {
  4. 1: 'value 1',
  5. 2: 'value 2',
  6. 3: 'value 3',
  7. }
  8.  
  9. print(dictionary)
  10. # {'key 1': 'value 1', 'key 2': 'value 2', 'key 3': 'value 3'}
  11. print(dictionary[1])
  12. # value 1
  13.  
  14. dictionary = {
  15. 'key 1': 'value 1',
  16. 'key 2': 'value 2',
  17. 'key 3': 'value 3',
  18. }
  19.  
  20. print(dictionary)
  21. # {'key 1': 'value 1', 'key 2': 'value 2', 'key 3': 'value 3'}
  22. print(dictionary['key 2'])
  23. # value 2
  24.  
  25. # Alternatively
  26.  
  27. # When we write dictionary in this form below keys can't
  28. # be integers (as compared to the first example)
  29. # change key1, key2, key3 to 1, 2, 3 respectively
  30. # When keys are integers, 'SyntaxError: keyword can't be
  31. # an expression' is prompted in the console.
  32. # This means keys can only be a set of alphabet or alphanumeric name or
  33. # key which is converted to a string.
  34. dictionary = dict(key1='value 1', key2='value 2', key3='value 3')
  35. print(dictionary)
  36. # {'key1': 'value 1', 'key2': 'value 2', 'key3': 'value 3'}
  37. print(dictionary['key2'])
  38. # value 2
  39.  
  40. dictionary = dict(name='Osagie', age=25, country='Nigeria')
  41. print(dictionary)
  42. # {'name': 'Osagie', 'age': 25, 'country': 'Nigeria'}
  43. print(dictionary['name'])
  44. # Osagie
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement