如何在python中处理字典的多个键? [英] How to handle multiple keys for a dictionary in python?

查看:108
本文介绍了如何在python中处理字典的多个键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找如何在找到重复键的情况下为Dict中的单个键添加多个val的方法.

I've been searching about how to go for adding multiple val for single keys in a Dict if a duplicate key is found.

让我们举个例子:

list_1 = ['4', '6' ,'8', '8']
list_2 = ['a', 'b', 'c', 'd']
new_dict = dict(zip(list_1,list_2))
...output...
{'8': 'd', '4': 'a', '6': 'b'}

预期输出:

{'8': 'c,d', '4': 'a', '6': 'b'}

为了处理上述两个列表并将它们组合成一个字典,我将面临一定的挑战,即在字典的键"中不能有两个8,这是默认行为,我知道为什么! !

In order to process the above two list and combine them into one dict, i would face a certain challenge that we can't have two 8's in the 'key' of dict, which is a default behavior and i understand why !!

存在一些用于处理这种情况的选项:

Some of the options that exists to process such scenario are :

1)查找dict中是否已经存在密钥",如果是,则将新值附加到密钥"

1) Find if 'key' already exists in dict, if yes, then append the new val to 'key'

2)创建一个可变对象来引用每个键,这样您就可以拥有多个dup键~~不是我的用例

2) Create a mutable object to reference each key and in that way you can have multiple dup keys ~~Not really my use case

那么,如何使用选项#1获得预期的输出?

So, how can i go about for expected output using option#1 ?

推荐答案

defaultdict/dict.setdefault

让我们跳进去吧

defaultdict/dict.setdefault

Let's jump into it:

  1. 连续迭代项目
  2. 附加属于同一键的字符串值
  3. 完成后,遍历每个键值对并将所有内容结合在一起,以获得最终结果.

from collections import defaultdict

d = defaultdict(list)   
for i, j in zip(list_1, list_2):
    d[i].append(j)

defaultdict使事情变得简单,并且追加效率很高.如果您不想使用defaultdict,请改用dict.setdefault(但这效率更低):

The defaultdict makes things simple, and is efficient with appending. If you don't want to use a defaultdict, use dict.setdefault instead (but this is a bit more inefficient):

d = {}
for i, j in zip(list_1, list_2):
    d.setdefault(i, []).append(j)

new_dict = {k : ','.join(v) for k, v in d.items()})
print(new_dict)
{'4': 'a', '6': 'b', '8': 'c,d'}


熊猫DataFrame.groupby + agg

如果要获得高性能,请尝试使用熊猫:


Pandas DataFrame.groupby + agg

If you want performance at high volumes, try using pandas:

import pandas as pd

df = pd.DataFrame({'A' : list_1, 'B' : list_2})
new_dict = df.groupby('A').B.agg(','.join).to_dict()

print(new_dict)
{'4': 'a', '6': 'b', '8': 'c,d'}

这篇关于如何在python中处理字典的多个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆