简体   繁体   English

将字典项目附加到Python中的列表

[英]Append dict items to a list in Python

I have a dict which consists 我有一个包括

docs[infile]={'tf':{}, 'idf':{},'words':[], 'tf_idf':{}}

and I have a list that I want to pass some of the dict's items 我有一个清单,我想通过字典的一些项目

the sub-dicts tf_idf AND idf contain data such as {(word, number),(word, number),...} 子字典tf_idf和idf包含诸如{{word,number),{word,number),...}之类的数据

I need to store in the list both tf_idf and idf items. 我需要在列表中同时存储tf_idf和idf项目。 This code stores only one of those 2 sub-dicts. 此代码仅存储这两个子字典之一。

templist=[]
for key in docs: #stores data in separate list
    TF_IDF_buffer = docs[key]['tf_idf'].items()
    templist.append(TF_IDF_buffer)

Is it possible to store both of them in the list ? 是否可以将它们都存储在列表中?

This joins the two sequences of items, keeping duplicated keys: 这将连接两个项目序列,并保留重复的键:

templist=[]
for key, value in docs.items():
    tf_idf = list(value['tf_idf'].items())
    idf = list(value['idf'].items())
    templist.append(tf_idf + idf)

I think something like this should be what you are looking for 我认为这样的事情应该是您想要的

templist=[]
for key in docs: #stores data in separate list
    for word in docs[key]['words']:
         idf = docs[key]['idf']
         tf_idf = docs[key]['tf_idf']
         temp_list.append((word, tf_idf, idf))

However, I also saw some of your other questions on this forum. 但是,我还在该论坛上看到了您的其他一些问题。 I think your structure of nested lists and dicts is somewhat complicated. 我认为您的嵌套列表和字典的结构有些复杂。 For instance, your list of words, is duplicated by the keys in idf and tf_idf . 例如,单词列表由idftf_idf的键重复。

You may want to consider using a more Object Oriented approach. 您可能要考虑使用一种更加面向对象的方法。

You could define a class like this: 您可以定义一个这样的类:

class Document:
     def __init__(self, words, idf, tf_idf):
         self.words = words
         self.idf = idf
         self.tf_idf = tf_idf

Also, from my memory of using NLP, I remember that using collections.defaultdict can be quite useful (especially if your idf and tf_idf dictionaries are sparse). 另外,从使用NLP的记忆中,我记得使用collections.defaultdict可能会非常有用(尤其是如果您的idftf_idf字典稀疏时)。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM