通过在python中修改现有字典来创建新字典

2024-09-28 22:20:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段口述如下

querydict = {u'variantcategoryitem_formset_0-0-variant_category_item_price': [u''], u'variantcategoryitem_formset_0-0-variant_category_item_quantity': [u''], u'variantcategoryitem_formset_0-0-variant_category_item_name': [u'hurray'], }

所以从上面的字典中,如果它没有price, quantity字段的值,我应该将值添加为0(quantity), 0.0(price)

像下面这样

^{pr2}$

但是它不起作用,我可以看到没有数量和价格值的字典,所以如果价格和数量在querydict中,'',那么任何人都可以通过将price和quantity更新为0.0到0来更正上面的逻辑并创建新的dict吗?在


Tags: name数量字典价格itempricequantityvariant
2条回答

问题是querydict包含一个空字符串的列表,因此if not querydict[key]的计算结果总是False,因为有一个项的列表不是错误的值。在

>>> bool([u''])
True

应将条件更改为:

^{pr2}$
  • 第二,在循环中,总是重写if elif条件中设置的值,因此将最后一条语句放在else块中。

  • 最后,您在'variant_category_item_qunatity'中出现了一个打字错误:

工作版本:

querydict = {u'variantcategoryitem_formset_0-0-variant_category_item_price': [u''], u'variantcategoryitem_formset_0-0-variant_category_item_quantity': [u''], u'variantcategoryitem_formset_0-0-variant_category_item_name': [u'hurray'], }
new_dict = {}
for key, value in querydict.iteritems():

    if 'variant_category_item_quantity' in key: #Typo in quantity spelling in your code
        if querydict[key] == [u'']:
            new_dict[key] = 0

    elif 'variant_category_item_price' in key:
        if querydict[key] == [u'']:
            new_dict[key] = 0.0

    # You need an else condition here, otherwise you'll overwrite the
    # values set in if-elif's         
    else:
         new_dict[key] = value
print new_dict

几个问题:

  1. 您在第一个ifvariant_category_item_qunatity处有打字错误,应该是quantity

  2. 您的item是无符号字符串的列表,因此必须与正确的类型进行比较。

  3. 我建议在dict中使用update(),这样更容易理解。。。

解决方法如下:

querydict = {u'variantcategoryitem_formset_0-0-variant_category_item_price': [u''], u'variantcategoryitem_formset_0-0-variant_category_item_quantity': [u''], u'variantcategoryitem_formset_0-0-variant_category_item_name': [u'hurray'], }


new_dict = {}

for key, value in querydict.iteritems():
    # Need to check variant_category_item_qunatity or variant_category_item_price exists in the key, because as u can observe there will be many quantity, price fields in the querydict like variantcategoryitem_formset_0-0-variant_category_item_price, variantcategoryitem_formset_1-1-variant_category_item_price, etc.

    if 'variant_category_item_quantity' in key:
        # If key exists and if equal to ''(empty string) update the new-dict with this key and value as 0(same in case of price below)
        if querydict[key] == [u'']:
            new_dict.update({key: 0})
    elif 'variant_category_item_price' in key:
        if querydict[key] == [u'']:
            new_dict.update({key: 0.0})
    # Update the entire new_dict with remaining values
    else:
        new_dict.update({key:value})

print new_dict

输出:

^{pr2}$

相关问题 更多 >