forked from zhanghe06/python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_dict.py
More file actions
141 lines (123 loc) · 2.88 KB
/
test_dict.py
File metadata and controls
141 lines (123 loc) · 2.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# encoding: utf-8
"""
将两个list组合为dict
"""
__author__ = 'zhanghe'
import itertools
import json
def test_01():
"""
key value 数量相等
"""
list_a = ['a', 'b', 'c']
list_b = ['10', '20', '30']
print dict(zip(list_a, list_b))
print dict(zip(list_a[::-1], list_b))
def test_02():
"""
key 数量小于 value
"""
list_a = ['a', 'b', 'c']
list_b = ['10', '20', '30', '50']
print dict(zip(list_a, list_b))
print dict(zip(list_a[::-1], list_b))
def test_03():
"""
key 数量大于 value
"""
list_a = ['a', 'b', 'c', 'd']
list_b = ['10', '20', '30']
print dict(zip(list_a, list_b))
print dict(zip(list_a[::-1], list_b))
def test_group():
"""
测试分组
"""
a = [
{
"update_time": "2016-08-17 13:51:54",
"name": "尺寸",
"value": "小",
"create_time": "2016-08-17 13:51:54",
"id": 1,
"product_id": 1
},
{
"update_time": "2016-08-17 13:51:54",
"name": "尺寸",
"value": "大",
"create_time": "2016-08-17 13:51:54",
"id": 2,
"product_id": 1
},
{
"update_time": "2016-08-17 13:51:54",
"name": "颜色",
"value": "蓝",
"create_time": "2016-08-17 13:51:54",
"id": 3,
"product_id": 1
},
{
"update_time": "2016-08-17 13:51:54",
"name": "颜色",
"value": "绿",
"create_time": "2016-08-17 13:51:54",
"id": 4,
"product_id": 1
},
{
"update_time": "2016-08-17 13:51:55",
"name": "颜色",
"value": "红",
"create_time": "2016-08-17 13:51:55",
"id": 5,
"product_id": 1
}
]
result = dict([(g, [i['value'] for i in list(k)]) for g, k in itertools.groupby(a, lambda x: x['name'])])
print json.dumps(result, indent=4, ensure_ascii=False)
result = [({'name': g, 'value': [i['value'] for i in list(k)]}) for g, k in itertools.groupby(a, lambda x: x['name'])]
print json.dumps(result, indent=4, ensure_ascii=False)
if __name__ == '__main__':
test_01()
test_02()
test_03()
test_group()
"""
测试结果:
{'a': '10', 'c': '30', 'b': '20'}
{'a': '30', 'c': '10', 'b': '20'}
{'a': '10', 'c': '30', 'b': '20'}
{'a': '30', 'c': '10', 'b': '20'}
{'a': '10', 'c': '30', 'b': '20'}
{'c': '20', 'b': '30', 'd': '10'}
{
"尺寸": [
"小",
"大"
],
"颜色": [
"蓝",
"绿",
"红"
]
}
[
{
"name": "尺寸",
"value": [
"小",
"大"
]
},
{
"name": "颜色",
"value": [
"蓝",
"绿",
"红"
]
}
]
"""