Advertisement
makispaiktis

Dictionary Methods

Jul 22nd, 2024
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | None | 0 0
  1. # 1. Keys, Values, Items
  2. d1 = {'Name':'Thomas', 'Age':25, 'Country':'India', 'Class':'Data Science', 'Grade':8.75}
  3. keys = list(d1.keys())
  4. values = list(d1.values())
  5. items = list(d1.items())
  6. print(keys, '\n', values, '\n', items, '\n\n')
  7.  
  8. print(f"{keys[0]}\n{values[0]}\n{items[0]} ---> {items[0][0]} and {items[0][1]}")
  9.  
  10.  
  11.  
  12. # 2. Update (like replace), get, clear
  13. d2 = {'Name':'Felix', 'Country':'Portugal', 'Grade':9.15}
  14. d1.update(d2)
  15. print(d1, '\n')
  16.  
  17. print(d1.get('Name'), d1.get('Age'), d1.get('Grade'), d1.get('Gender'))
  18. print(d1['Name'], d1['Age'], d1['Grade'], '\n')
  19.  
  20. print(d1.clear())
  21.  
  22.  
  23.  
  24. # 3. Pop (remove by key) vs popitem (remove last pair every time)
  25. d3 = {'Name':'Thomas', 'Age':25, 'Country':'India', 'Class':'Data Science', 'Grade':8.75, 'Region':'Athens', 'YearsAtWork':5}
  26. d3.pop('Name')
  27. d3.pop('Country')
  28. print(d3, '\n')
  29.  
  30. d3.popitem()
  31. print(d3)
  32.  
  33.  
  34.  
  35. # 4. Copy and add pairs
  36. d4 = {'Name':'Thomas', 'Age':25, 'Country':'India', 'Class':'Data Science', 'Grade':8.75, 'Region':'Athens', 'YearsAtWork':5}
  37. d5 = d4.copy()
  38.  
  39. d4.popitem()
  40. d4['Name'] = 'Sabrina'
  41.  
  42. d5['Height'] = '185 cm'
  43. print(d4, '\n', d5)
  44.  
  45.  
  46.  
  47. # 5. Create a dictionary with the SAME VALUE for every key
  48. array = ['String1', 'String2', 'String3', 'String4', 'String5']
  49. value = 'Hello'
  50. d6 = {key:value for key in array}
  51. print(d6)
  52. d7 = dict.fromkeys(array, value)
  53. print(d7)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement