简体   繁体   English

python字典,每个键或类有两个值?

[英]python dictionary with two values for each key or class?

I need a data structure of this form: 我需要这种形式的数据结构:

   test_id1: resultValue, timeChecked
   test_id2: resultValue, timeChecked
   test_id3: resultValue, timeChecked
   test_id4: resultValue, timeChecked
   ...

up until now I have dealt with it by just using a dictionary with key value for the id and the result. 到目前为止,我只使用一个带有id值和结果的键值的字典来处理它。 But I would like to add the time I checked. 但我想补充一下我检查的时间。 What would be the best way to do this? 最好的方法是什么? Can I make the value a tuple? 我可以将值设为元组吗? Or is a new class better suited in this case? 或者是一个更适合这种情况的新班级? What would my class need to look like to accommodate the above? 我的班级需要什么来容纳上述内容?

One lightweight alternative to making a class that both 1) retains the simplicity of a tuple and 2) allows named (as opposed to positional) field access is namedtuple . 一种制造类既1)一种轻量级替代保留的元组的简单性和2)允许命名(相对于位置)字段的访问受到namedtuple

from collections import namedtuple

Record = namedtuple("Record", ["resultValue", "timeChecked"])
s = {"test_id1": Record("res1", "time1"), "test_id2": Record("res2", "time2")}

You can now use the values in this dict as if you had a class with the resultValue and timeChecked fields defined... 您现在可以使用此dict的值,就好像您有一个定义了resultValuetimeChecked字段的类一样...

>>> s["test_id1"].resultValue
'res1'

...or as simple tuples: ......或者作为简单的元组:

>>> a, b = s["test_id1"]
>>> print a, b
res1 time1

Can I make the value a tuple? 我可以将值设为元组吗?

Yes, and I'm not really sure why you don't want to. 是的,我不确定你为什么不想这样做。 If it's to make look-ups easier to read, you can even make the value another dictionary. 如果要使查找更容易阅读,您甚至可以使该值成为另一个字典。

{"test_id1" : (resultValue, timeChecked)}

or 要么

{"test_id1" : {"resultValue": resultValue, "timeChecked" : timeChecked }}

I think a whole new class is overkill for this situation. 我认为一个全新的课程对于这种情况来说是过度的。

You could also use a pandas DataFrame for your whole structure. 您还可以将pandas DataFrame用于整个结构。 It's probably waaaay overkill unless you're planning to do some serious data processing, but it's a nice thing to know about and directly matches your problem. 除非你打算做一些严肃的数据处理,否则它可能会过度杀戮,但要了解并直接匹配你的问题是一件好事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM