-2

Below is my code. I need some help to fetch the expected output.

name = []

backup = []

data = {
    "details": [
        {"vm": "disk1", "backupname": "backup1"},
        {"vm": "disk1", "backupname": "backup2"}, 
        {"vm": "disk1", "backupname": "backup3"},
        {"vm": "disk2", "backupname": "newbackup"}
    ]
}

for detail in data["details"]:
    name.append(detail['vm'])
    backup.append(detail['backupname'])

print(name)

print(backup)

Actual output:

name = ['disk1', 'disk1', 'disk1', 'disk2']

number of backup = ['backup1', 'backup2', 'backup3', 'newbackup']

Expected output:

name = ['disk1', 'disk2']

number of backup = [3, 1]

I'm unable to get the count of backup taken for each disk.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Beginner
  • 1
  • 3
  • I suggest you try to create this output instead: `{'disk1': 3, 'disk2': 1}`. You should use something with `+ 1` in your loop instead of `append`. – mkrieger1 Aug 20 '20 at 08:07
  • You can refer to this link https://stackoverflow.com/questions/2161752/how-to-count-the-frequency-of-the-elements-in-an-unordered-list – itas97 Aug 20 '20 at 08:07

1 Answers1

1
name = {}
backup = {}

data = {
"details":[{"vm":"disk1","backupname":"backup1"},{"vm":"disk1","backupname":"backup2"}, 
{"vm":"disk1","backupname":"backup3"},{"vm":"disk2","backupname":"newbackup"}]}
for detail in data["details"]:
    if not name.get(detail['vm']):
      name[detail['vm']] = 1
    else :
      name[detail['vm']] += 1

print(name)

Output:

{'disk1': 3, 'disk2': 1}
SeongJaeSong
  • 211
  • 2
  • 10