【发布时间】:2018-07-28 00:27:06
【问题描述】:
我有一个默认字典,其中键是数字,值是列表,每个列表有两个条目。我想根据第一个条目按条件过滤。我在这里尝试使用建议:filter items in a python dictionary where keys contain a specific string
这是我使用的代码:
circuits = {k:v for k,v in circuits.iteritems() if (v[0]+weightlimit <= histotal) in k}
这段代码运行后,我在代码中唯一使用字典的地方收到了关于缺少键的错误。
这当然意味着有问题,因为 defaultdict 不会那样做。所以看来字典理解会把defaultdict改成字典。
这里最好的做法是什么?使用不同的过滤方法是否更有效,或者以某种方式将我的字典转换为 defaultdict 是否更有效?还有什么好方法呢?
谢谢!
【问题讨论】:
-
你能发布示例输入和所需的输出吗?
-
请不要发布代码链接。在问题本身中将代码作为格式化文本发布。提供minimal reproducible example
标签: python dictionary iteration defaultdict dictionary-comprehension