Sayantan Ghosh
Sayantan Ghosh

Reputation: 338

How to combine two values into a single key for a dictionary in python?

So, I have a dictionary in the following format. The key is a concatenated string and the value is a list of tuples.

dictionary = {'ABC|1':[(1,10),(5,16),(15,30)],
              'ABC|2':[(9,18),(78,10),(5,10)],
              'XYZ|1':[(45,56),(72,79),(81,98),(100,120)],
              'XYZ|2':[(11,26),(78,99),(105,119),(150,178)],..........}

Now, I want to change the key from 'ABC|1' to 'ABC' and combining the two values of 'ABC|1' and 'ABC|2' into a single value for the key 'ABC'. Thus, the final_dict should look like this:

final_dict = {'ABC':[(1,10),(5,16),(15,30),(9,18),(78,10),(5,10)],
              'XYZ':[(45,56),(72,79),(81,98),(100,120),(11,26),(78,99),(105,119),(150,178)],....}

The approach I am trying is as follows:

final_dict = dict()
for key in dictionary.keys():
  new_key = key.split('|')[0]
  if new_key not in final_dict:
    value = list()
  if new_key in key:
    value.append(dictionary[key])

However, this is not working. Can anybody provide me a suggestion to do this? Without using pandas.

Upvotes: 0

Views: 1408

Answers (3)

kederrac
kederrac

Reputation: 17322

you have to build your final_dict by assigning to you desired key the proper value, because your initial dict has aleadry lists as value you have to extend with them the final_dict values:

final_dict = dict()
for key in dictionary.keys():
    new_key = key.split('|')[0]
    if new_key not in final_dict:
        final_dict[new_key]= dictionary[key]
    else:
        final_dict[new_key].extend(dictionary[key])

Upvotes: 1

Anmol Agrawal
Anmol Agrawal

Reputation: 904

Just some variation in your code:

dictionary = {'ABC|1':[(1,10),(5,16),(15,30)],
              'ABC|2':[(9,18),(78,10),(5,10)],
              'XYZ|1':[(45,56),(72,79),(81,98),(100,120)],
              'XYZ|2':[(11,26),(78,99),(105,119),(150,178)]}

final_dict = {}
for key in dictionary.keys():
    new_key = key.split('|')[0]
    if new_key not in final_dict:
        final_dict[new_key] = dictionary[key]
    else:
        final_dict[new_key].extend(dictionary[key])

I tried the above code and gives this output:

{'XYZ': [(45, 56), (72, 79), (81, 98), (100, 120), (11, 26), (78, 99), (105, 119), (150, 178)], 'ABC': [(1, 10), (5, 16), (15,
 30), (9, 18), (78, 10), (5, 10)]}

Upvotes: 1

hiro protagonist
hiro protagonist

Reputation: 46859

this is a variant:

from collections import defaultdict

dct = defaultdict(list)
for key, value in dictionary.items():
    new_key = key.split('|')[0]
    dct[new_key].extend(value)

where i use collections.defaultdict.

your solution is close but judging from your desired output you want list.extend and not list.append.

Upvotes: 1

Related Questions