简体   繁体   English

Python:将与键相关联的列表值存储在字典中

[英]Python: Storing a list value associated with a key in dictionary

I know how python dictionaries store key: value tuples. 我知道python字典如何存储键:值元组。 In the project I'm working on, I'm required to store key associated with a value that's a list. 在我正在进行的项目中,我需要存储与列表值关联的键。 ex: key -> [0,2,4,5,8] where, key is a word from text file the list value contains ints that stand for the DocIDs in which the word occurs. 例如:key-> [0,2,4,5,8]其中,key是文本文件中的单词,列表值包含表示该单词所在的DocID的整数。

as soon as I find the same word in another doc, i need to append that DocID to the list. 一旦我在另一个文档中找到相同的单词,就需要将该DocID附加到列表中。

How can I achieve this? 我该如何实现?

You can use defauldict, like this: 您可以使用默认值,如下所示:

>>> import collections
>>> d = collections.defaultdict(list)
>>> d['foo'].append(9)
>>> d
defaultdict(<type 'list'>, {'foo': [9]})
>>> d['foo'].append(90)
>>> d
defaultdict(<type 'list'>, {'foo': [9, 90]})
>>> d['bar'].append(5)
>>> d
defaultdict(<type 'list'>, {'foo': [9, 90], 'bar': [5]})

This post was helpful for me to solve a problem I had in dynamically creating variable keys with lists of data attached. 这篇文章对我解决在动态创建带有附加数据列表的变量键时遇到的问题很有帮助。 See below: 见下文:

import collections

d = collections.defaultdict(list)
b = collections.defaultdict(list)
data_tables = ['nodule_data_4mm_or_less_counts','nodule_data_4to6mm_counts','nodule_data_6to8mm_counts','nodule_data_8mm_or_greater_counts']

for i in data_tables:
    data_graph = con.execute("""SELECT ACC_Count, COUNT(Accession) AS count
                                            FROM %s
                                            GROUP BY ACC_Count"""%i)
    rows = data_graph.fetchall()
    for row in rows:
        d[i].append(row[0])
        b[i].append(row[1])

print d['nodule_data_4mm_or_less_counts']
print b['nodule_data_4mm_or_less_counts']

Which outputs the data lists for each key and then can be changed to a np.array for plotting etc. 它输出每个键的数据列表,然后可以更改为np.array进行绘图等。

>>>[4201, 1052, 418, 196, 108, 46, 23, 12, 11, 8, 7, 2, 1]
>>>[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16]

This would be a good place to use defaultdict 这将是使用defaultdict的好地方

from collections import defaultdict

docWords = defaultdict(set)
for docID in allTheDocIDs:
    for word in wordsOfDoc(docID):
        docWords[word].add(docID)

you can use a list instead of a set if you have to 您可以使用列表而不是集合

Something like this? 像这样吗


word = 'something'
l = [0,2,4,5,8]
myDict = {}
myDict[word] = l

#Parse some more

myDict[word].append(DocID)

I once wrote a helper class to make @Vinko Vrsalovic`s answer easier to use: 我曾经写过一个帮助器类,以使@Vinko Vrsalovic的答案更易于使用:

class listdict(defaultdict):
    def __init__(self):
        defaultdict.__init__(self, list)

    def update(self, E=None, **F):
        if not E is None:
            try:
                for k in E.keys():
                    self[k].append(E[k])
            except AttributeError:
                for (k, v) in E:
                    self[k].append(v)
        for k in F:
            self[k].append(F[k])

This can be used like this: 可以这样使用:

>>> foo = listdict()
>>> foo[1]
[]
>>> foo.update([(1, "a"), (1, "b"), (2, "a")])
>>> foo
defaultdict(<type 'list'>, {1: ['a', 'b'], 2: ['a']})

If i get your question right,You can try this , 如果我的问题正确,您可以尝试一下,

           >>> a=({'a':1,'b':2});
           >>> print a['a']
            1
           >>> a.update({'a':3})
           >>> print a['a']
            3
            >>> a.update({'c':4})
            >>> print a['c']
             4

This will work with older versions of python 这将适用于旧版本的python

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python将数据框存储为与字典中的键相关联的值 - python storing a dataframe as value associated with key in dictionary Python在字典中查找与多个值关联的键 - Python find key in dictionary associated with a number of value 如何从字典中的字典迭代和 append 键值对并将具有相同键的值存储到列表 python - How to iterate and append key value pairs from a dictionary within a dicionary and storing values with same key into a list python 用另一个列表遍历字典列表,并找到相关的键值 - Iterating through dictionary lists with another list, and finding associated key of value Python:获取与字典中的单个键关联的值的列表 - Python: Getting a list of values associated with a single key in a dictionary 搜索我的python字典中是否存在列表并附加到关联的键 - Searching if a list exists in my python dictionary and append to the associated key 在 python 中存储 100 万个键值对的列表 - Storing a list of 1 million key value pairs in python 在 python 的另一个字典列表中搜索列表字典的键值 - searching key value of dictionary of list in another list of dictionary in python python在列表中过滤不同的字典键值 - python filter distinct dictionary key value in list 列出为字典理解中每个键的值-Python - List as value per key in dictionary comprehension - Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM