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

时间:2013-12-02 12:03:16

标签: python dictionary extend

我有一个dict如下

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)

如下所示

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_qunatity' 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 not querydict[key]:
            new_dict[key] = 0
    elif 'variant_category_item_price' in key:
        if not querydict[key]:
            new_dict[key] = 0.0
    # Update the entire new_dict with remaining values
    new_dict[key] = value

但是它不起作用,我能够看到没有数量和价格值的字典,所以任何人都可以通过将价格和数量更新为0.0到0来纠正上述逻辑并使用querydict值创建新的dict,如果它们是''中的querydict

2 个答案:

答案 0 :(得分:0)

问题是querydict包含一个包含空字符串的列表,因此if not querydict[key]始终评估为False,因为包含一个项目的列表不是虚假值。

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

您应该将条件更改为:

if querydict[key] == [u'']
  • 其次在你的循环中你总是覆盖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 :(得分:0)

几个问题:

  1. 您在第if variant_category_item_qunatity处有拼写错误quantity

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

  3. 我建议将update()与dict一起使用,理解起来更清楚......

  4. 以下是解决方案:

    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
    

    <强>输出:

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