Skip to content

Commit 6fceb4b

Browse files
add list2dict in utils.py, add its unittest
1 parent 72e8096 commit 6fceb4b

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

pysenal/utils/utils.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# -*- coding: UTF-8 -*-
2+
import copy
23
from typing import Iterable
34

45

@@ -24,3 +25,26 @@ def get_chunk(l, n):
2425

2526
if chunk:
2627
yield chunk
28+
29+
30+
def list2dict(l, key, pop_key=False):
31+
"""
32+
convert list of dict to dict
33+
:param l: list of dict
34+
:param key: key name, which value of dict in list as returned dict key
35+
:param pop_key: whether pop the key in list of
36+
:return: assembled dict
37+
"""
38+
if type(l) not in {list, tuple}:
39+
raise TypeError('input must in list or tuple type')
40+
d = {}
41+
for item in l:
42+
if not isinstance(item, dict):
43+
raise TypeError('item {0} is not dict'.format(item))
44+
if key not in item:
45+
raise KeyError('key is not in item')
46+
new_item = copy.deepcopy(item)
47+
if pop_key:
48+
new_item.pop(key)
49+
d[item[key]] = new_item
50+
return d

tests/utils/test_utils.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,24 @@ def test_get_chunk():
3535
assert next(chunk_g3, [10, 100, 200])
3636
with pytest.raises(StopIteration):
3737
next(chunk_g3)
38+
39+
40+
def test_list2dict():
41+
l1 = [{'pid': '1', 'title': 'haha'}, {'pid': '2', 'title': 'lalala'}]
42+
expected_l1 = {'1': {'pid': '1', 'title': 'haha'}, '2': {'pid': '2', 'title': 'lalala'}}
43+
ret_l1 = list2dict(l1, 'pid')
44+
l1[0]['pid'] = '11'
45+
l1[1]['pid'] = '22'
46+
47+
assert ret_l1 == expected_l1
48+
with pytest.raises(KeyError):
49+
list2dict(l1, 'patent_id')
50+
l1.append(1)
51+
with pytest.raises(TypeError):
52+
list2dict(l1, 'pid')
53+
54+
l2 = [{'name': 'a', 'count': 11}, {'name': 'b', 'count': 2}]
55+
expected_l2 = {'a': {'count': 11}, 'b': {'count': 2}}
56+
assert list2dict(l2, 'name', pop_key=True) == expected_l2
57+
with pytest.raises(TypeError):
58+
list2dict(1, 'pid')

0 commit comments

Comments
 (0)