In the case of duplicate keys in the dictionary type, how to concatenate them without overwriting them.

Asked 2 years ago, Updated 2 years ago, 31 views

Python I'm just a beginner.

environment:Python 2.7.6

I'm currently trying to merge multiple dictionary arrays, but I'm having trouble overwriting them because the keys are the same.

In other words,

dic={'A':'1', 'B':'2'}
dic1 = {'A': '3', 'B': '2', 'C': '4'}

Add these two dictionary arrays together

dic_rev = {'A': '1,3', 'B': '2', 'C': '4'}

I would like to

python

2022-09-30 21:19

3 Answers

If you merge the values of multiple dictionary arrays, I think you should use defaultdict.

 from collections import defaultdict

default_dict_values(*dictts):
    r=defaultdict(set)
    For directions:
        fork, vind.iteritems():
            r[k].add(v)
    return

dic = {'A': '1', 'B': '2'}
dic1 = {'A': '3', 'B': '2', 'C': '4'}
dic_merged=merge_dict_values(dic,dic1)
printdic_merged
# defaultdict(<type'set'>, {'A':set(['1','3'], 'C':set(['4'], 'B':set(['2']})})

Thus, we merged each dictionary type sequence.Then concatenate the values of the set type into a string.

dic_rev={k:','.join(v)fork, vindic_merged.iteritems()}
printdic_rev
# {'A': '1,3', 'C': '4', 'B': '2'}

Since we used set for the above resolution, we cannot guarantee the order of concatenated values.

If you want to match the order of each parameter, you should store it in the list as follows:

def merge_dict_values(*dictts):
    Change to r=defaultdict(list)#list
    For directions:
        fork, vind.iteritems():
            if v not inr [k]: # Add if this value is not present
                r[k].append(v)
    return


2022-09-30 21:19

"I am not sure what I want to do with ""merge"", but I think I can get the expected results with the code below."
Try not to concatenate with commas when the values are the same.

>>dic={'A':'1', 'B':'2'}
>>dic1 = {'A': '3', 'B': '2', 'C': '4'}
>>dic_rev={}
>> forkin set (dic) | set (dic1):
...     vl = [ ]
...     ifkindic:
...         vl.append(dic[k])
...     if kindic1 and dic1[k]not in vl:
...         vl.append(dic1[k])
...     dic_rev[k]=','.join(vl)
...
>>dic_rev
{'A': '1,3', 'B': '2', 'C': '4'}


2022-09-30 21:19

Use reduce as a separate solution.

def merge_dict(d,k,v):
  ifkind:
    if d[k]!=v:
      d[k]+=', '+v
  else:
    d[k] = v
  returned

reduce(lambdad,(k,v):merge_dict(d,k,v),dic.items()+dic1.items(),dict())
= > {'A': '1,3', 'C': '4', 'B': '2'}


2022-09-30 21:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.