Python Forum
combining lists in a dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
combining lists in a dictionary
#1
i have a dictionary in which the values of each element is a list. i am trying to come up with a not complicated comprehension that gives me a list that is all those values concatenated. the order of concatenation does not matter since the resulting list will be sorted. i tried sum() thinking that since it does + operations, it could be applied to lists to achieve concatenation, but i got a type error from that.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
sum(dict.values(), [])
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
why was sum() designed to need the 2nd argument? why was sum() not designed to do its thing across any number of arguments like min() and max() were? my new mysum() function does.

def mysum(*args):
    if len(args)<1:
        return 0
    if isinstance(args[0],(list,tuple,set,frozenset,dict)):
        args=[x for x in args[0]]
    if args:
        s=args[0]
        for x in args[1:]:
            s+=x
        return s
    return 0
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
I don't know. Why do you have to complain about everything in Python?
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
just straightly pass the dict to sum function. 2nd arguments is just optional to add the result. hope this will help.

>>> dict = {'a':[1,2,3,4,5], 'b':[5,10,15,20]}
>>> sum(dict['a'])
15
>>> sum(dict['a'], 5)
20
>>> sum(dict['b'])
50
>>> sum(dict['b'], 50)
100
>>> 
Reply
#6
i know how sum() works. i forgot about setting the 2nd argument to the initial value since i rarely use sum(). i use min(), max(), all(), and any() more often and was thinking that way.

i'm not complaining. i am more curious about the decisions because i have used a few other languages of nearly this model (not the syntax model, but the run-time model). and, i even designed one (but never implemented it). my curiosity also includes the syntax, like that question i recently had about the ambiguity if the ":" was omitted to start a new block. the creator side of my brain is always active (hence my nickname).
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#7
There are many built-in tools for achieving desired result. One just need to find most suitable for use case. I would add to ichabod801 following possibilities:

Concat and sort in one go (using built-in itertools.chain):

sorted(i for i in itertools.chain(*d.values()))
As operation in question is not sum per se but concat (concatenation is what the + operator is written to do for Python's built-in lists). So why don't use built-in operator.concat? Combined with functools.reduce (used to be built-in function, now moved to functools) one can:

functools.reduce(operator.concat, d.values())
If interested how Python sum() evolved and what options were discussed one can look into mail.python.org archive. I provide one example thread named summing a bunch of numbers (or whatevers). But up until resignation simple explanation to 'why' is: 'this is the way Guido wanted (decided)'

If I try mysum function on dictionary d = {'a': [4], 'b': [2], 'c': [3]} with mysum(d) then 'abc' is returned. Is it expected behaviour?
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#8
I like the solution with chain, but isn't chain already a generator? Can't you just do:

sorted(itertools.chain(*d.values()))
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#9
(Nov-04-2019, 03:02 PM)ichabod801 Wrote: I like the solution with chain, but isn't chain already a generator? Can't you just do:

sorted(itertools.chain(*d.values()))

Mea culpa. You are absolutely right.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#10
You can get rid of the *:

sorted(itertools.chain.from_iterable(d.values()))
BTW: You will find inconsistencies in all existing languages (natural and logical). Humans make mistakes, humans build machines with bugs and humans are creating language definitions with "bugs". This is our nature. You can't be perfect and if you think you got the perfect solution, someone else is coming and will show all your mistakes you made, but even his improvement will never be perfect.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  combining lists stealth 3 1,602 Feb-08-2022, 04:36 AM
Last Post: deanhystad
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,353 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  Help: for loop with dictionary and nested lists mart79 1 1,858 Apr-12-2020, 02:52 PM
Last Post: TomToad
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,247 Mar-20-2019, 08:01 PM
Last Post: stillsen

Forum Jump:

User Panel Messages

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