gpt4 book ai didi

python - 重组字典键值对的更好方法?

转载 作者:太空宇宙 更新时间:2023-11-04 08:16:39 25 4
gpt4 key购买 nike

我从一个像这样的简单 python 字典开始:-

In [29]: date_dict
Out[29]:
{'2003-06-24': 2,
'2003-08-13': 1,
'2003-08-19': 2,
'2003-08-22': 1,
'2003-08-24': 5}

键是日期,值是整数。

我的目标是将这个字典中的数据重组为:-

{'datetime': ['2003-08-13',
'2003-08-19',
'2003-06-24',
'2003-08-24',
'2003-08-22'],
'observations': [1, 2, 2, 5, 1]}

维护datetime键持有的列表和observations键持有的列表之间的数据关系。

这是我完成此任务的解决方案:-

In [35]: new_dict
Out[35]: {'datetime': [], 'observations': []}

In [36]: for key, value in date_dict.iteritems():
....: new_dict['datetime'].append(key)
....: new_dict['observations'].append(value)

In [37]: new_dict
Out[37]:
{'datetime': ['2003-08-13',
'2003-08-19',
'2003-06-24',
'2003-08-24',
'2003-08-22'],
'observations': [1, 2, 2, 5, 1]}

我的问题是 - 是否有替代方法(更好,如果更有效)执行此操作?

(请注意,保持两个列表之间的数据关系至关重要,即在原始 date_dict 中,“2003-08-24”对应值“5”。数据重组后,第 3 个索引“日期时间”列表是“2003-08-24”,它与“观察列表”的第三个索引正确对应为“5”。)

最佳答案

也许:

new_dict = {'datetime': date_dict.keys(), 'observations': date_dict.values()}

如果您需要订购,请尝试使用 OrderedDict而不是听写:

Return an instance of a dict subclass, supporting the usual dict methods. An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

关于python - 重组字典键值对的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13372146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com