Safe Khan
Safe Khan

Reputation: 41

how to delete a key in a list of dicts?

def get_all_cust_info():
    """function displays data as a list of dict of base  data"""
    reader = csv.DictReader(open("base data.csv", "rb"))
    all_rows = list()
    for row in reader:
    all_rows.append(row)
    return all_rows

first line output of get_all_cust_info().

   [{'totcust': '2', 'delfee': '1308', 'bskt_bnd': '0', 'distribution ': '>1', 'totords': '199', 'netsales': '1851'}, .......] 

I want to create a new function which deletes keys('delfee' and 'netsales') and also add new key 'order value'.This is what I have done

    def cust_state():
        s = get_all_cust_info()
        for d in s:
            if d.has_key('delfee'):
               del d['delfee']
               print s  

But I am getting this error.

  AttributeError: 'list' object has no attribute 'has_key'

Would really appreciate help on this.

Upvotes: 0

Views: 372

Answers (1)

zhangyangyu
zhangyangyu

Reputation: 8620

if s.has_key('delfee'):

should be:

if d.has_key('delfee'):


def cust_state():
        s = get_all_cust_info()
        for d in s:
            if 'delfree' in d:
                del d['delfree']
            if 'netsales' in d:
                del d['netsales']
            d['ordervalue'] = something
        return s

Upvotes: 1

Related Questions