通过DictWriter(Python)将字典写入CSV文件(Writing a dictionary to a CSV file via DictWriter (Python))
DictWriter似乎并不适合我。
当前代码:
myfile = open('hashdict.csv', 'wb') fieldnames = ('md5', 'value') myWriter = csv.DictWriter(myfile, fieldnames=fieldnames) headers = dict((n,n) for n in fieldnames) myWriter.writerow(headers) for n in dictToSearch: myWriter.writerow(n) myfile.close()
追溯:
Traceback (most recent call last): File "hash.py", line 42, in <module> myWriter.writerow(n) File "C:\Python27\lib\csv.py", line 148, in writerow return self.writer.writerow(self._dict_to_list(rowdict)) File "C:\Python27\lib\csv.py", line 144, in _dict_to_list ", ".join(wrong_fields)) ValueError: dict contains fields not in fieldnames: d, 1, a, 5, 0, d, 0, a, 1, 7 , 0, e, 5, e, a, 9, f, e, b, 6, f, 7, 9, 6, 1, 3, 6, 3, f, 6, d, 9
字母数字字符来自MD5哈希,但这就是我能告诉你的全部内容。 我查看了文档,似乎无法理解它。 我要做的是从名为dictToSearch的字典中创建一个CSV文件。
在此先感谢您的帮助,如果您需要任何其他信息,请告诉我们。
链接到完整代码: http : //pastebin.com/A3E4AJfV
DictWriter just doesn't seem to be working for me.
Current code:
myfile = open('hashdict.csv', 'wb') fieldnames = ('md5', 'value') myWriter = csv.DictWriter(myfile, fieldnames=fieldnames) headers = dict((n,n) for n in fieldnames) myWriter.writerow(headers) for n in dictToSearch: myWriter.writerow(n) myfile.close()
Traceback:
Traceback (most recent call last): File "hash.py", line 42, in <module> myWriter.writerow(n) File "C:\Python27\lib\csv.py", line 148, in writerow return self.writer.writerow(self._dict_to_list(rowdict)) File "C:\Python27\lib\csv.py", line 144, in _dict_to_list ", ".join(wrong_fields)) ValueError: dict contains fields not in fieldnames: d, 1, a, 5, 0, d, 0, a, 1, 7 , 0, e, 5, e, a, 9, f, e, b, 6, f, 7, 9, 6, 1, 3, 6, 3, f, 6, d, 9
The alphanumerical characters are from an MD5 hash, but that's about all I can tell you. I've looked at the documentation and can't seem to make sense of it. What I'm trying to do is make a CSV file out of the dictionary called dictToSearch.
Thanks in advance for any help, and let me know if you need any other information.
Link to full code: http://pastebin.com/A3E4AJfV
原文:
最满意答案
我尝试使用条件值来注释查询,当标记位于您提供的列表中时,该条件值变为true
from django.db.models import Case, When, IntegerField Thing.objects.annotate(tag_is_known=Case( When(tags__name__in=['foo', 'bar'], then=1), default=0, output_field=IntegerField() ))
接下来,我们使用我们称为
tag_is_known
注释来对order_by()
进行排序:Thing.objects.annotate(tag_is_known=...).order_by('tag_is_known')
布尔版本
Thing.objects.annotate(tag_is_known=Case( When(tags__name__in=['foo', 'bar'], then=True), default=False, output_field=BooleanField() ))
I'd try annotate the query with the conditional value that turns true when the tag is in the list you provide
from django.db.models import Case, When, IntegerField Thing.objects.annotate(tag_is_known=Case( When(tags__name__in=['foo', 'bar'], then=1), default=0, output_field=IntegerField() ))
Next we use that annotation we called
tag_is_known
to sort withorder_by()
:Thing.objects.annotate(tag_is_known=...).order_by('tag_is_known')
Boolean version
Thing.objects.annotate(tag_is_known=Case( When(tags__name__in=['foo', 'bar'], then=True), default=False, output_field=BooleanField() ))
相关问答
更多-
填充ManyToManyField(Populate a ManyToManyField)[2022-04-27]
当您创建具有ManyToMany字段的数据库记录时,您无法正常执行此操作。 您必须创建对象,然后将事物添加到ManyToMany字段。 像这样的东西。 class Author(models.Model): name = models.CharField(max_length=100) class Article(models.Model): name = models.CharField(max_length=100) authors = models.ManyToManyFiel ... -
编辑 : 抱歉,是我的错! 现在这应该工作。 我在家里试过...... Album.objects.filter( published=True, albumregionreleasedate__region__name='Europe' ).order_by( 'albumregionreleasedate__digital_release_date' ) 这是对未来疑虑的一些帮助 希望它现在有效! EDIT: Sorry, my mistake! Now this should ...
-
尝试: current_course = Course.objects.get(pk=course) modules = Module.objects.all().filter(course=current_course) Try: current_course = Course.objects.get(pk=course) modules = Module.objects.all().filter(course=current_course)
-
如何在具有ManyToManyField的django模型中过滤查询集?(How to filter a queryset in django model having a ManyToManyField?)[2022-08-20]
要筛选特定用户的消息,您的代码看起来是正确的(它只是有一个错字)。 它应该是这样的: queryset = Messages.objects.filter(user=user) 如果你想使用userID (我会亲自把它重命名为user_id ): queryset = Messages.objects.filter(user.id=user_id) 这两者都会为您提供一个查询集,它是一个类似于结构的数组。如果您需要更精细的值,则可以继续进行过滤。 例如: queryset.filter(message ... -
你有什么应该工作。 只需确保使用实际的QuerySet ,而不是相关的管理器: # don't forget '.all()' return ClassB.objects.exclude(restrictions__in=self.restrictions.all()) 这将排除任何具有任何A实例限制的B实例。 What you have should work. Just make sure you use an actual QuerySet, not the related manager: # d ...
-
Django ManyToManyField(Django ManyToManyField)[2021-12-21]
那么,它应该更像这样: models.py class Tag(models.Model): name = models.CharField(max_length=200) class Poll(models.Model): topic = models.CharField(max_length=200) tags = models.ManyToManyField(Tag) in views.py: poll = Poll(topic="My topic") poll.sav ... -
如果没有现成的小部件可以做你想要的(而且我认为没有),那么你需要自己编写。 不幸的是,Django文档没有向您展示如何执行此操作,但通过查看复制现有窗口小部件并对其进行修改的源代码forms/widgets.py来解决问题并不难。 If there are no existing widgets that do what you want (and I don't think there are) then you'll need to write your own. Unfortunately, the ...
-
'ManyToManyField'查询('ManyToManyField' queries)[2022-03-16]
评论后更新: 关于多对多关系的文档 def get_intolerancias(self): alimentos = self.ingredientes.all() # Give us all alimento of a recetta intolerancias = [] for a in alimentos: intolerancias.append(a.get_intolerancia_display()) ... -
通过ManyToManyField = Value订购django查询集(Order a django queryset by ManyToManyField = Value)[2024-03-01]
我尝试使用条件值来注释查询,当标记位于您提供的列表中时,该条件值变为true from django.db.models import Case, When, IntegerField Thing.objects.annotate(tag_is_known=Case( When(tags__name__in=['foo', 'bar'], then=1), default=0, output_field=IntegerField() )) 接下来,我们使用我们称为tag_is_k ... -
这是你需要的吗? from django.db.models import Count options = Option.objects.filter(tags__in=entry.tags.all()) options = options.annotate(tag_count=Count('tags')) options = options.filter(tag_count__gte=2) Is this what you need? from django.db.models import Coun ...