-2

How can I remove a key in a dic in a list

for exemple

My_list= [{'ID':0,'Name':'Paul','phone':'1234'},{'ID':1,'Name':'John','phone':'5678'}]

I want to remove in ID 1 the phone key

My_list= [{'ID':0,'Name':'Paul','phone':'1234'},{'ID':1,'Name':'John'}]

thanks in advance for your help

  • possible duplicate of [get key by value in dictionary](http://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary) – Zero Piraeus May 24 '14 at 18:19

2 Answers2

0

When the id you are looking for matches 1, then reconstruct the dictionary excluding the key phone, otherwise use the dictionary as it is, like this

l = [{'ID': 0, 'Name': 'Paul', 'phone': '1234'},
     {'ID': 1, 'Name': 'John', 'phone': '5678'}]

k, f = 1, {"phone"}
print([{k: i[k] for k in i.keys() - f} if i["ID"] == k else i for i in l])
# [{'phone': '1234', 'ID': 0, 'Name': 'Paul'}, {'ID': 1, 'Name': 'John'}]

Here, k is the value of ID you are looking for and f is a set of keys which need to be excluded in the resulting dictionary, if the id matches.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • >>> print[{k: i[k] for k in i.viewkeys() - f} if i["ID"] == k else i for i in l] I have SyntaxError: invalid syntax I use Python 3.x – user3224813 May 22 '14 at 13:09
  • @user3224813 If you are using Python 3.x, please check the updated answer. Also, you need to explicitly mention the version in the question. That would be good for the answerers. – thefourtheye May 23 '14 at 00:21
0

Just iterate through the list, check whether if 'ID' equals to 1 and if so then delete the 'phone' key. This should work:

for d in My_list:
    if d["ID"] == 1:
        del d["phone"]

And finally print the list:

print My_list