Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
690 views
in Technique[技术] by (71.8m points)

python-3.x - 如何从数据创建字典(How to create a dictionary from data)

I am trying to create a function that creates a dictionary for each day (first column), and records the feedback of the day.

(我正在尝试创建一个功能,该功能为每天(第一列)创建一个字典,并记录当天的反馈。)

The main thing im having an issue with is how to detect that it is a new day and to create a new dictionary.

(我遇到的主要问题是如何检测到这是新的一天并创建新的字典。)

Here is the data:

(数据如下:)

0   21  M   34  P
0   22  F   12  N
0   28  M   67  P
1   18  M   22  P
1   21  F   88  P
1   34  F   97  N
2   55  M   21  P
2   65  M   32  P
2   33  F   55  N
2   48  F   7   P

?

()

  ask by rochimer translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With combination of csv.reader + collections.defaultdict + collections.Counter objects:

(结合使用csv.reader + collections.defaultdict + collections.Counter对象:)

from collections import defaultdict, Counter
import csv
from io import StringIO

data = '''0   21  M   34  P
0   22  F   12  N
0   28  M   67  P
1   18  M   22  P
1   21  F   88  P
1   34  F   97  N
2   55  M   21  P
2   65  M   32  P
2   33  F   55  N
2   48  F   7   P'''

d = defaultdict(Counter)
reader = csv.reader(StringIO(data), skipinitialspace=True, delimiter=' ')
for row in reader:
    d[row[0]][row[4]] += 1
d = {int(k): dict(v) for k, v in d.items()}

print(d)

The output:

(输出:)

{0: {'P': 2, 'N': 1}, 1: {'P': 2, 'N': 1}, 2: {'P': 3, 'N': 1}}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...