Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - remove item from Dict/List [duplicate]

My Webservice call to Mongo returns following JSON. I need to iterate this JSON value and remove the Item - product_language as it contain NULL/Empty string.

ANy thoughts on how to do this?

Python 3.4 version.

{

"prod_doc_key" : "613509",

"metadata" : {
    "channel_availability_for" : {
        "description" : "Kiosk and Web",
        "id" : 0
    },

    "dd_sold_out_flag" : 0,
    "dd_units_sold_flag" : 0,
    "display_type_id" : {
        "id" : 0
    },
    "preorder_flag" : 0,
    "price_in_cart_flag" : 0,
    "product_language" : "",
    "product_type" : {
        "id" : 0,
        "name" : "Product"
    },
    "promotion_flag" : 0,
    "published" : 1,
    "rebate_flag" : 0


}

}

like image 687
user3092876 Avatar asked Dec 08 '15 22:12

user3092876


People also ask

How do I remove duplicates from a dictionary list?

Using unique everseen() for Removing duplicate dictionaries in a list. everseen() function is used to find all the unique elements present in the iterable and preserving their order of occurrence. Hence it remembers all elements ever seen in the iterable.

Does dictionary remove duplicates Python?

Create a dictionary, using the List items as keys. This will automatically remove any duplicates because dictionaries cannot have duplicate keys.

How do you remove redundant data in Python?

You can remove duplicates from a Python using the dict. fromkeys(), which generates a dictionary that removes any duplicate values. You can also convert a list to a set. You must convert the dictionary or set back into a list to see a list whose duplicates have been removed.


2 Answers

Load it with json, then remove the key if it's empty:

import json
item =json.loads(src)
if 'product_language' in item and not item['product_language']:
    item.pop('product_language')

in Python, empty strings are equal to False.

like image 199
Ali Nikneshan Avatar answered Sep 29 '22 19:09

Ali Nikneshan


use json module to load the json.

import json

with open('demo.txt','r+') as f:
    dic=json.load(f)

    try:
        if dic['metadata']["product_language"]:
            del dic['metadata']["product_language"]
    except KeyError:
        print "Key doesn't exist"
    print dic

Note that, here dic is a dictionary, you can be sure about it by printing type(dic). So, you can can perform any dictionary operation on it, for example, I deleted a key of dic. To iterate through the dic, do:

for key,value in dic.iteritems():
    #do_something
like image 41
Ahsanul Haque Avatar answered Sep 29 '22 18:09

Ahsanul Haque