Skip to content

Instantly share code, notes, and snippets.

@SZ-Edward
Created December 7, 2017 10:38
Show Gist options
  • Save SZ-Edward/22d6df04a7f7bdc7fea006b8509771f0 to your computer and use it in GitHub Desktop.
Save SZ-Edward/22d6df04a7f7bdc7fea006b8509771f0 to your computer and use it in GitHub Desktop.
Implement a data structure(dict-like), you can get value by index or key. Just like data[index] or data[key].
import unittest
def get_of_data(data, key):
if type(key) is int:
if key < len(data[1]):
k = data[1][key]
return data[0][k]
raise IndexError('The index is out of range.')
elif type(key) is str:
return data[0][key]
def set_of_data(key, value, data=None):
if type(key) not in [int, str]:
raise TypeError('Unsupport type! Only support int or str.')
if data is not None:
data[0].update({key: value})
index = len(data[1]) # get the index of next item
data[1].update({index: key})
else:
data = [{key: value}, {0: key}]
return data
class TestDataStructureMethods(unittest.TestCase):
def test_set_of_data(self):
d = set_of_data('a', 3)
self.assertEqual(d, [{'a': 3}, {0: 'a'}])
d = set_of_data('b', 5, d)
self.assertEqual(d, [{'a': 3, 'b': 5}, {0: 'a', 1: 'b'}])
with self.assertRaises(TypeError):
set_of_data((), 10, d)
def test_get_of_data(self):
d = [{'a': 3, 'c': 9, 'b': 5, 'd': 1}, {0: 'a', 2: 'b', 3: 'c', 4: 'd'}]
self.assertEqual(get_of_data(d, 'c'), 9)
self.assertEqual(get_of_data(d, 2), 5)
with self.assertRaises(IndexError):
get_of_data(d, 9)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment