Home > database >  Match with the last occurrence of same key in a dictionary?
Match with the last occurrence of same key in a dictionary?

Time:01-24

I have the following input:

test = [{1:"i am Mike"},{3:"i am 20 years old"},{1:"i live in greece"},{7:"i love pizza"},{9:"i love basketball"}]

I want to find the first and the last occurrence of each key and then i want to group all the information between the first and the last occurrence and more specifically the string. I want the following output:

test = [{1:"i am Mike i am 20 years old i live in greece"},{7:"i love pizza"},{9:"i love basketball"}]

CodePudding user response:

something like this :

test = [{1:"i am Mike"},{3:"i am 20 years old"},{1:"i live in greece"},{7:"i love pizza"},{9:"i love basketball"}]
result = {}
for dic in test:
    for k,v in dic.items():
        result[k] = result.get(k, '')  v   ','

print(result)

output:

>>>
{1: 'i am Mike,i live in greece,', 3: 'i am 20 years old,', 7: 'i love pizza,', 9: 'i love basketball,'}

CodePudding user response:

The no libraries or anything fancy aproach:

test = [{1: "i am Mike"}, {3: "i am 20 years old"}, {1: "i live in greece"}, {7: "i love pizza"},
    {9: "i love basketball"}]

tracking = [] 
output_str = []
result = []
for d in test:
    key, value = tuple(d.items())[0]
    output_str.append(value)
    if key in tracking:
        start = tracking.index(key)
        result  = [{k: v} for (k, v) in zip(tracking[:start], output_str[:start])]
        tracking = tracking[start:]
        output_str = output_str[start:]
        result.append({key: ''.join(output_str)})
        tracking.clear()
        output_str.clear()
    else:
        tracking.append(key)

result  = [{k: v} for (k, v) in zip(tracking, output_str)]
print(result)

This doesnt support 1 2 2 4 1 it will only merge 2 2

CodePudding user response:

First associate the starting and ending index to each key in separate dictionaries. Then combine these into non-overlapping ranges identifying the first key of each range. Finally extract the strings from the dictionaries in each range:

starts = { k:len(test)-i for i,d in enumerate(reversed(test),1) for k in d }
ends   = { k:i for i,d in enumerate(test,1) for k in d }
ranges = [(0,)]
ranges.extend( (k,starts[k],ends[k]) for i,d in enumerate(test) 
                for k in d if i==ranges[-1][-1] )
merged = [ {g:" ".join(d[k] for d in test[s:e] for k in d)} 
           for g,s,e in ranges[1:] ]

output:

print(merged)
[{1: 'i am Mike i am 20 years old i live in greece'}, 
 {7: 'i love pizza'}, 
 {9: 'i love basketball'}]
  •  Tags:  
  • Related