在Python中将两个字典合并以创建一个新字典:

huangapple go评论56阅读模式
英文:

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).

huangapple
  • 本文由 发表于 2023年3月1日 08:12:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75598498.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定