基于公共键与字典列表相交
假设我有两个字典列表:
dates = [{'created':'2010-12-01'},{'created':'2010-12-02'},....]
elts = [{'created':'2010-12-01', 'key1':'val1', 'key2':'val2'}, {'created':'2010-12-05','key1':'val1'}]
日期列表是一堆连续的日期。
elts 列表可以是从 1 到 len(dates) 之间的任何位置,我想做的基本上是填充 elts,以便它有一个日期的字典,无论是否有其他键。
这是我天真的解决方案:
for d in dates:
for e in elts:
if d['created'] == e['created']:
d.update(dict(key1=e['key1']))
因此我将有一个最终的数组 d,其中包含每个字典中的所有日期,但可能/可能没有其他键/值。
什么是好的“Pythonic”解决方案?
Let's say I have two list of dicts:
dates = [{'created':'2010-12-01'},{'created':'2010-12-02'},....]
elts = [{'created':'2010-12-01', 'key1':'val1', 'key2':'val2'}, {'created':'2010-12-05','key1':'val1'}]
The dates list is a bunch of contiguous dates.
The elts list can be anywhere from 1 to len(dates), and what I want to do is basically pad elts so that it has a dict for a date regardless if there're other keys.
This is my naive solution:
for d in dates:
for e in elts:
if d['created'] == e['created']:
d.update(dict(key1=e['key1']))
Thus I will have a final array d
with all dates in each dict
, but there may/may not be other key/vals.
What's a good 'pythonic' solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为您的问题有点偏离,因为您的解决方案似乎并没有真正解决您的问题,但如果您想在
elts
中为dates
中的每个日期创建一个条目code> 尚未出现在elts
中,您可以使用此:这是一个 http://codepad.org 代码片段显示此代码片段有效:http://codepad.org/n4NbjvPM
Your question is a little off, I think, since your solution doesn't seem to actually address your question, but if you wanted to create an entry in
elts
for every date indates
that does not already appear inelts
, you could use this:Here's a http://codepad.org snippet that shows this snippet in effect: http://codepad.org/n4NbjvPM
编辑:不同的解决方案:
创建一组已经获得的日期:
这只会迭代每个列表一次,而不是迭代日期中每个日期的 elts。
EDIT: Different solution:
Make a set of dates you've already got:
This only iterates over each list once, rather than iterating over elts for each date in dates.
我可能会把这些列表做成字典。
如果您随后需要它再次按顺序成为字典列表,您可以轻松做到这一点:
如果您除了合并它们之外不做任何其他事情,那么您的解决方案可能更容易阅读。但我怀疑,在这种情况下,字典列表并不是一种非常方便的数据格式。
I'd probably make those lists dictionaries instead.
If you then need it to be a list of dicts in order again, you can do that easily:
If you are not doing anything else than merging them, your solution might be more easily readable, though. But lists of dictionaries is not a very handy format for data in this case, I suspect.
也许我读错了,但在我看来,你的代码的最终结果是,对于 elts 中的每个字典,你真的只想从 elts 复制该字典来覆盖日期中相应的字典。
那时,日期字典反映了我认为您想要的内容。
Maybe I've misread, but it seems to me that the end result of your code is that, for every dict in elts, you really want to just copy that dict from elts to overwrite the corresponding dict in dates.
At that point, it's the dates dictionary that reflects what I think you want.