[Tutor] Question on List of Dict

Sunil Tech sunil.techspk at gmail.com
Fri Sep 19 13:41:22 CEST 2014


Danny i did it like this

result_dict = {}
for i in tes:
    if i['a'] in result_dict:
        temp = result_dict[i['a']]
        temp['b'].append(i['b'])
        temp['c'].append(i['c'])
        temp['a'] = i['a']
        result_dict[i['a']] = temp
    else:
        result_dict[i['a']] = {
            'b': [i['b']],
            'c': [i['c']],
            'a': i['a']}
pprint.pprint(result_dict.values())

result is

[{'a': 1, 'b': ['this', 'is', 'sentence'], 'c': [221, 875, 874]},
 {'a': 2, 'b': ['this', 'another', 'word'], 'c': [215, 754, 745]}]

any can one improve this method in terms of performance, etc..

Thanks every one.

On Fri, Sep 19, 2014 at 1:22 PM, Danny Yoo <dyoo at hashcollision.org> wrote:

>
> On Sep 19, 2014 12:28 AM, "Danny Yoo" <dyoo at hashcollision.org> wrote:
> >
> >
> > >        {'a': 2, 'b': 'another', 'c': 754},
> > >        {'a': 2, 'b': 'word', 'c': 745}
> > >
> >
> > > if the value of the 'a' is same, then all those other values of the
> dict should be merged/clubbed.
> >
> > Can you write a function that takes two of these and merges them?
> Assume that they have the same 'a'.  Can you write such a function?
>
> Specifically, can you write a function merge_two() such that:
>
>     merge_two({''b': 'another', 'c': 754}, {'b': 'word', 'c': 745})
>
> returns the merged dictionary:
>
>    {'b' : ['another', 'word'], 'c':[754, 745]}
>
> I'm trying to break the problem into simpler, testable pieces that you can
> solve.  The problem as described is large enough that I would not dare
> trying to solve it all at once.  If you have merge_two(), them you are much
> closer to a solution to the whole problem.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140919/362a916b/attachment.html>


More information about the Tutor mailing list