Python Forum
Dictionary iteration and creation a new dictionary from duplicates
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionary iteration and creation a new dictionary from duplicates
#1
Hello there,
need an explanation and help how to write a script.
I'm fetching data from OpenStack cinder volumes API. The result is a dictionary with rows of dictionaries.
Every row has specific couple objects which values can be duplicated in another row of the main dictionary.
for example:
{id:gf23gf, size:5}
{id:iu38gr, size:5}
{id:gf23gf, size:5}
{id:iu38gr, size:5}
{id:gf23gf, size:5}
{id:gf23gf, size:5}


My goal is to get these values to a new dictionary. For the same "id" values I need to sum "size" values and result must be as one dictionary row:
{gf23gf:20, iu38gr:10}

my script:
api = [c for c in cinder.volumes.list(search_opts={'all_tenants':1})]
new_dict = {}
for i in api:
....api_dict = {} #rows with dictionaries where is all api's data
........for k,v in api_dict_.iteritems():
............api_dict[k] = v
........id = api_dict['id']
........size = api_dict['size']
........new_dict[id] = size
........if id in new_dict.keys():
............new_dict[id] += size

as an output I have new_dict{}, but the summarization goes incorrect.
Thanks in advance.
Reply
#2
This is what your program does:
new_dict[id] = size
new_dict[id] += size
You logic should be similar to that shown below. For each id/size pair you either add the pair to the dictionary or you increase the size sum. You never do both.
try:
   new_dict[id] += size
KeyError:
   new_dict[id] = size
You can use the test if id in new_dict.keys(), but I think that is horribly inefficient.
Reply
#3
That is great and a helpful suggestion.
Your method gives a correct count.
Thanks so much.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Matching Data - Help - Dictionary manuel174102 1 354 Feb-02-2024, 04:47 PM
Last Post: deanhystad
  Dictionary in a list bashage 2 494 Dec-27-2023, 04:04 PM
Last Post: deanhystad
  filtering a list of dictionary as per given criteria jss 5 597 Dec-23-2023, 08:47 AM
Last Post: Gribouillis
  need to compare 2 values in a nested dictionary jss 2 797 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  Sort a list of dictionaries by the only dictionary key Calab 1 452 Oct-27-2023, 03:03 PM
Last Post: buran
  python dictionary is that a bug ? rmangla 2 547 Sep-27-2023, 05:52 AM
Last Post: DPaul
  python dictionary syntax nafshar 2 840 Apr-24-2023, 07:26 PM
Last Post: snippsat
  Printing specific values out from a dictionary mcoliver88 6 1,317 Apr-12-2023, 08:10 PM
Last Post: deanhystad
  How to add list to dictionary? Kull_Khan 3 951 Apr-04-2023, 08:35 AM
Last Post: ClaytonMorrison
  Dictionary freethrownucleus 3 65,153 Mar-22-2023, 08:26 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020