Skip to content

Commit 807bb8e

Browse files
authored
Create 如何把tuple轉成dictionary.md
1 parent 31f161b commit 807bb8e

1 file changed

Lines changed: 64 additions & 0 deletions

File tree

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# 如何把 tuple 轉成 dictionary
2+
3+
## 問題
4+
5+
我有一個 tuple list:
6+
7+
![clipboard.png](https://segmentfault.com/img/bVzgCO)
8+
9+
現在我想把這組 tuples 變成 dictionary 的 list, 類似的效果是這樣:
10+
11+
```python
12+
meat = [
13+
{
14+
"地區詞":"深圳福田區",
15+
"品牌詞":"TTM全身體檢",
16+
"疑問詞":"地址怎麼走",
17+
"價格詞":"價格要多少錢"
18+
},
19+
{
20+
"地區詞":"深圳保安區",
21+
"品牌詞":"TTM全身體檢",
22+
"疑問詞":"地址怎麼走",
23+
"價格詞":"要做多少項目"
24+
},
25+
.....
26+
]
27+
```
28+
29+
有什麼比較方便的方法?
30+
31+
問題出自 [segmentfault](https://segmentfault.com/q/1010000005983046/a-1020000005983077), by [jqlts1](https://segmentfault.com/u/jqlts1)
32+
33+
## 回答
34+
35+
```python
36+
names = 'area brand question price'.split()
37+
lst = [{name:value for name, value in zip(names, t)} for t in tlst]
38+
```
39+
40+
測試:
41+
42+
```python
43+
tlst = [('a1','b1','q1','p1'),
44+
('a2','b2','q2','p2'),
45+
('a3','b3','q3','p3')]
46+
47+
names = 'area brand question price'.split()
48+
lst = [{name:value for name, value in zip(names, t)} for t in tlst]
49+
50+
print(lst)
51+
```
52+
53+
結果:
54+
55+
```python
56+
[{'brand': 'b1', 'area': 'a1', 'question': 'q1', 'price': 'p1'}, {'brand': 'b2', 'area': 'a2', 'question': 'q2', 'price': 'p2'}, {'brand': 'b3', 'area': 'a3', 'question': 'q3', 'price': 'p3'}]
57+
```
58+
59+
改良(by [hsfzxjy](https://segmentfault.com/u/hsfzxjy):
60+
61+
```python
62+
names = 'area brand question price'.split()
63+
lst = [dict(zip(names, t)) for t in tlst]
64+
```

0 commit comments

Comments
 (0)