英文:
combining two dictionary to create a new dictionary in python
问题
我有一个将订单映射到货架的字典。
orders_to_bins={1: 'a', 2:'a', 3:'b'}
我有另一个字典显示订单中的物品。
items={1:[49,50,51,62],
2:[60,63,64,65],
3:[70,71,72,74]}
我需要创建一个新的字典,显示货架中的物品,如下所示。
items_in_bins={'a':[49,50,51,62,60,63,64,65],
'b':[70,71,72,74]}
我正在寻找如何从前两个字典中实现最后一个字典的提示或解决方案。
英文:
I have a dictionary that maps orders to bins.
orders_to_bins={1: 'a', 2:'a', 3:'b'}
I have another dictionary that shows the items in the orders.
items={1:[49,50,51,62],
2:[60,63,64,65],
3:[70,71,72,74]}
I need to create a new dictionary that shows the items in the bins like this.
items_in_bins={'a':[49,50,51,62,60,63,64,65],
'b':[70,71,72,74]}
I am looking for hints or solutions on how to achieve the last dictionary from the first two.
答案1
得分: 2
这个答案使用了一个defaultdict
,它实际上是一个常规的Python字典,其中每个新值都自动初始化为特定类型(在这种情况下是list
)。
对于orders_to_bins
中的每个(键,值)对(使用.items()
方法提取),我们扩展了特定键的items_in_bins
列表,该键是items
中的bin_name
。
代码示例如下:
from collections import defaultdict
items_in_bins = defaultdict(list)
for order, bin_name in orders_to_bins.items():
items_in_bins[bin_name].extend(items[order])
>> print(dict(items_in_bins))
{'a': [49, 50, 51, 62, 60, 63, 64, 65], 'b': [70, 71, 72, 74]}
请注意,在打印语句中,我将其转换回了常规的dict
以便阅读,但这并不是必要的。
此外,请注意,如果您不确定items
是否会被填充,您可以使用items.get(order, [])
而不是items[order]
来确保它不会在缺少键时失败。但这取决于您要做什么(即这是否是一个有效的错误)。
英文:
This answer uses a defaultdict
, which is essentially a regular python dictionary where every new value is automatically initialized to be a particular type (in this case list
).
For every (key, value)-pair in the orders_to_bins
(extracted with the .items()
method), we extend the items_in_bins
list for a particular key, which is the bin_name
from whatever is in items
.
Here is what that looks like:
from collections import defaultdict
items_in_bins = defaultdict(list)
for order, bin_name in orders_to_bins.items():
items_in_bins[bin_name].extend(items[order])
>>> print(dict(items_in_bins))
{'a': [49, 50, 51, 62, 60, 63, 64, 65], 'b': [70, 71, 72, 74]}
Note, in the print statement, I am making it back to a regular dict
for ease of reading, but that is not necessary.
Also note, if you are unsure if items will be populated, you could do items.get(order, [])
instead of items[order]
to ensure that it does not fail on missing keys. But, that is up to you and dependent on what you are trying to do (i.e. maybe that is a valid error).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论