python - 使用具有列表作为其值的唯一键创建一个 python 字典

标签 python

我想创建一个字典如下 -

{'a':[1, 2, 3, 4, 5], 'b':[1, 3, 5], 'c':[2, 3, 5]}

我的实现方式是

mydict = dict()
letters = ['a', 'b', 'a', 'c', 'a'] 

#please mark the list has multiple occurence of a, 
#hence I would want to check if a key with 'a' exists. Please do not advise to make the list unique. 
for l in letters:
    if not mydict.get(l):
        mydict[l] =  <values from another place via some filter>
    else:
        mydict[l].append(<values from another dict>)

有没有更好的方法来做到这一点?

最佳答案

是的,您可以使用 defaultdict :

示例代码:

»»» from collections import defaultdict

»»» mydict = defaultdict(list)

»»» letters = ['a', 'b', 'a', 'c', 'a'] 

»»» for l in letters:
   ....:     mydict[l].append('1')
   ....:     

»»» mydict
Out[15]: defaultdict(<type 'list'>, {'a': ['1', '1', '1'], 'c': ['1'], 'b': ['1']})

如果您需要将内容初始化为更高级的东西,您可以指定您自己的构造函数作为 defaultdict 的第一个参数。不过,将特定于上下文的参数传递给该构造函数可能会很棘手。

关于python - 使用具有列表作为其值的唯一键创建一个 python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16695514/

相关文章:

python - 我收到错误TypeError : 'int' object is not callable

python - SqlAlchemy - 什么时候应该创建新 session ?

javascript - Jupyter (IPython) notebook 中的交互式绘图,带有可拖动点,在拖动时调用 Python 代码

javascript - 使用 Python 3.5.1 和 Selenium 2.53.2 选择并单击网站按钮时出现问题

python - 将对象属性 (id) 或完整对象作为参数传递

python - 如何延迟 Python 中脚本的执行?

python - 为什么我的 isclass 函数会得到 false?

python - 在 python 中使用 scrapy 执行 Javascript 函数

python - Web 应用程序的高效 trie 存储

python - Python-打印回溯