首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何查找单键具有多个值的字典

如何查找单键具有多个值的字典
EN

Stack Overflow用户
提问于 2019-09-01 19:24:48
回答 4查看 77关注 0票数 1

我有两本不同的字典:

  • 它显示了品牌的名称和类型(即空气是品牌,鞋子是类型)

D1 = {'apple': 'phone', 'samsung': 'phone', 'LG': 'TV', 'sony': 'TV'}

  • 这显示了产品名称和为同一产品下的订单数量。

D2 = {'apple': 3, 'samsung': 5, 'LG': 1, 'sony': 2}

我想创造一个新的字典(不使用熊猫)的方式,它显示最受欢迎的品牌,为一个给定的类型和订购数量相同。最受欢迎的品牌被定义为拥有最全面订单的品牌。如果两个或两个以上的品牌(一个给定的类型)有相同数量的订单,选择任何人。

我试图合并两个字典,如下所示:

{'samsung': ['phone', 5], 'apple': ['phone', 3], 'sony': ['TV', 2], 'LG': ['TV', 1]}

我不确定这是不是正确的方法。如果是这样的话,我如何才能从这本字典中获得所需的数据?

我用来将两个字典合并为一个的代码:

代码语言:javascript
复制
d3={}
for key in (d2:keys()|d1.keys()):
  if key in d2: d3.setdefault(key, []).append(d2[key])
  if key in d1: d3.setdefault(key, []).append(d1[key])

预期结果:-

{'samsung': 5, 'sony': 2}

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2019-09-01 20:20:23

派对有点晚了,但我认为我的是迄今为止最简单的

代码语言:javascript
复制
D1 = {'apple': 'phone', 'samsung': 'phone', 'LG': 'TV', 'sony': 'TV'}
D2 = {'apple': 3, 'samsung': 5, 'LG': 1, 'sony': 2}

most_popular = {}

for brand, type_ in D1.items():
    orders = D2[brand]
    current_winner = most_popular.get(type_, None)
    if current_winner is None or orders > current_winner[1]:
        most_popular[type_] = (brand, orders)

result = {brand: orders for type_, (brand, orders) in most_popular.items()}

print(result)
# {'samsung': 5, 'sony': 2}

对于D1中的每个品牌类型对,它会检查是否没有该产品类型的条目(在这种情况下,我们将此类型),或者该品牌是否超过当前的订单条目(在这种情况下,我们用新品牌更新条目)。

最后一行将这些数据转换为结果的正确格式。

编辑:

设法将其压缩成一个非常脏的一行(不包括most_popular的初始赋值):

代码语言:javascript
复制
D1 = {'apple': 'phone', 'samsung': 'phone', 'LG': 'TV', 'sony': 'TV'}
D2 = {'apple': 3, 'samsung': 5, 'LG': 1, 'sony': 2}

most_popular = {}
result = {brand: orders for type_, (brand, orders) in {type_: (brand, D2[brand]) for brand, type_ in D1.items() if not most_popular.get(type_, None) or D2[brand] > most_popular.get(type_, None)[1]}.items()}

print(result)
# {'samsung': 5, 'sony': 2}
票数 1
EN

Stack Overflow用户

发布于 2019-09-01 19:49:58

这可能有点复杂,但这应该有效:

代码语言:javascript
复制
D1 = {'apple': 'phone', 'samsung': 'phone', 'LG': 'TV', 'sony': 'TV'}
D2 = {'apple': 3, 'samsung': 5, 'LG': 1, 'sony': 2}

categories = {}
res = {}

for key in D1:
    if D1[key] not in categories:
        categories[D1[key]] = [key]
    else:
        categories[D1[key]].append(key)

for cat in categories:
    currMax = {'brand': '', 'value': 0}
    for key in D2: 
        if key in categories[cat] and D2[key] > currMax['value']:
            currMax = {'brand': key, 'value': D2[key]} 
    res[currMax['brand']] = currMax['value']

print(res)

它打印:

{“索尼”:2,“三星”:5}

说明:第一个循环为每个类别创建一个字典,将列表中的品牌作为值。第二个类别遍历所有类别,并找到最大值的类别。特别是第二个循环有点冗长..。

票数 1
EN

Stack Overflow用户

发布于 2019-09-01 19:58:28

哦,看来我有点晚了。:P

代码语言:javascript
复制
D1 = {'apple': 'phone', 'samsung': 'phone', 'LG': 'TV', 'sony': 'TV'}
D2 = {'apple': 3, 'samsung': 5, 'LG': 1, 'sony': 2}

#creates list of lists
mylist = [list(x) for x in zip(D1,D1.values())]
#adds thrid value to lists in list (source countities in D2)
mylist = [x + [D2.get(x[0])] for x in mylist]

#creates empty result dictionary
result = {}
#loops through unique value in dictionary on index position 1 (phone, tv's etc.)
for element in list(set([x[1] for x in mylist])):
    #temporary saves current winner
    current_max = 0
    current_winner = ""
    #loops through the lists in the list of lists
    for sublist in mylist:
        #groups the lists by skipping lists which are not in the current category(e.g. TVs)
        if sublist[1]==element:
            #checks if the current lists has a higher maximum value than the currently best
            if sublist[2]>current_max:
                #if yes, it replaces the current winner in the group
                current_max = sublist[2]
                current_winner = sublist[0]
    #adds the current winner to the result dictionary, then starts looking for the winner in the next group
    result[current_winner] = current_max

#prints result
print(result)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57748849

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档