Advertisement
Guest User

Untitled

a guest
Aug 26th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. let swappingKV = function(values){
  2. let myData = [
  3. {first: 1},
  4. {second: 2},
  5. {third: 3},
  6. {fourth: 4},
  7. {fifth: 5}
  8. ];
  9. let newDictionary = {}; //We need this to store after we swap the object.
  10. for (let k in values){
  11. newDictionary[values[k]] = k; //Swapping.
  12. }
  13. console.log(myData) //Printing original data
  14. return newDictionary; //returning swapped and filled objects
  15. console.log(swappingKV({first:1, second:2, third:3, fourth:4, fifth:5}));
  16.  
  17. // I also tried swapping using temp variable. My idea was to store the first object into the first temp variable
  18. // then swap them. That took longer than anticipated.
  19.  
  20.  
  21. -----------------------------------------------------------------------------------------------------------------------
  22.  
  23. //I practiced similar concept in Python as well. I tried using same concept as above.
  24.  
  25. newObject = {}
  26. originalObject = {'first': 1, 'second':2, 'third':3, 'fourth':4, 'fifth':5}
  27. for keys, values in originalObject.items(): //items() is in-built for dictionary in python
  28. newObject[values] = keys //Same concept as above. Swapping by setting values to keys.
  29. print newObject //Printing swapped object
  30.  
  31.  
  32. // There are several ways we could swap this. The other way I was thinking was we could directly write for-in
  33. // loop and declare value:key with items() function at the end. That is another quickest way I thought of doing it.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement