I haveing trouble understanding python dictonary
let say I have a dictornary called data that looks like this:
{ "computers": [
{"Netbios_Name0": "apple1", "User_Domain0": "paradise", "User_Name0": "adam", "SMS_Installed_Sites0": "heaven", "Client_Version0": "5.00.9058.1018"},
{"Netbios_Name0": "apple2", "User_Domain0": "paradise", "User_Name0": "lilith", "SMS_Installed_Sites0": "heaven", "Client_Version0": "5.00.9040.1044"},
{"Netbios_Name0": "apple3", "User_Domain0": "paradise", "User_Name0": "eve", "SMS_Installed_Sites0": "heaven", "Client_Version0": "5.00.9068.1026"}
]}
and I want to remove apple2 so my end results looks like this:
{ "computers": [
{"Netbios_Name0": "apple1", "User_Domain0": "paradise", "User_Name0": "adam", "SMS_Installed_Sites0": "heaven", "Client_Version0": "5.00.9058.1018"},
{"Netbios_Name0": "apple3", "User_Domain0": "paradise", "User_Name0": "eve", "SMS_Installed_Sites0": "heaven", "Client_Version0": "5.00.9068.1026"}
]}
I suspect I have to do something like this:
for item in data['computers']:
if "apple2" in item['Netbios_Name0']:
item.pop() # or del data[item]
But I can’t get it to work.
>Solution :
You can use remove():
data = { "computers": [
{"Netbios_Name0": "apple1", "User_Domain0": "paradise", "User_Name0": "adam", "SMS_Installed_Sites0": "heaven", "Client_Version0": "5.00.9058.1018"},
{"Netbios_Name0": "apple2", "User_Domain0": "paradise", "User_Name0": "lilith", "SMS_Installed_Sites0": "heaven", "Client_Version0": "5.00.9040.1044"},
{"Netbios_Name0": "apple3", "User_Domain0": "paradise", "User_Name0": "eve", "SMS_Installed_Sites0": "heaven", "Client_Version0": "5.00.9068.1026"}
]}
for item in list(data['computers']):
if 'apple2' in item['Netbios_Name0']:
data['computers'].remove(item)
data
Output:
{'computers': [{'Netbios_Name0': 'apple1',
'User_Domain0': 'paradise',
'User_Name0': 'adam',
'SMS_Installed_Sites0': 'heaven',
'Client_Version0': '5.00.9058.1018'},
{'Netbios_Name0': 'apple3',
'User_Domain0': 'paradise',
'User_Name0': 'eve',
'SMS_Installed_Sites0': 'heaven',
'Client_Version0': '5.00.9068.1026'}]}