Python Dictionary Aggregation??

Sdílet
Vložit
  • čas přidán 3. 09. 2023
  • ⭐ Join the Byte Club to practice your Python skills! ($2.99/mo): / @b001
    🐦 Follow me on Twitter: / b001io
    Background Music:
    Gentle Lo-Fi Vlog Background Music | Cookies by Alex-Productions | onsound.eu/
    Music promoted by www.free-stock-music.com
    Creative Commons / Attribution 3.0 Unported License (CC BY 3.0)
    creativecommons.org/licenses/...

Komentáře • 241

  • @V0W4N
    @V0W4N Před 10 měsíci +540

    python just keeps throwing more niche and actually useful stuff at me the longer i study it

    • @eldebtor6973
      @eldebtor6973 Před 4 měsíci +1

      in R these would be data.frames and this would be more cognitively straight forward

    • @DoRullings
      @DoRullings Před 3 měsíci +5

      @vow4n I have a strong suspicion that all these guys who obviously have a strong urge to write comments everywhere, all the time, where they try to imply that they are experienced rust developers, actually suffering from microphallus.

  • @tahitsharif3723
    @tahitsharif3723 Před 10 měsíci +405

    That’s really cool. As someone who’s beginning to learn python the way you weight it so smoothly is nice

    • @Holyluckdan
      @Holyluckdan Před 10 měsíci +6

      Would recommend reading python for everybody

    • @jerusalema9155
      @jerusalema9155 Před 2 měsíci

      How did you understand really still confusing to me

  • @skan8494
    @skan8494 Před 6 měsíci +86

    I didn't even know that dictionary comprehension even existed

    • @cycrothelargeplanet
      @cycrothelargeplanet Před 3 měsíci

      Same, I only knew generator and list comprehensions up until this

  • @RS-fz4ps
    @RS-fz4ps Před 5 měsíci +19

    As a senior programmer, this is a beautiful explanation. Thank you for this.

    • @paulblart7378
      @paulblart7378 Před měsícem

      And the fact that a senior programmer has nothing to say about this terrible code proves how doomed programming jobs are

  • @foshizzlebizz4470
    @foshizzlebizz4470 Před měsícem +3

    I think this CZcams short just saved my life

  • @evanbelcher
    @evanbelcher Před 7 měsíci +23

    Counter. Use Counter. It's in the stdlib

  • @yeetskeet691
    @yeetskeet691 Před 7 měsíci +5

    List and Dictionary comprehension is one of my favorite parts of python. Thats the reason why I opt to use python for quick scripting over Lua sometimes

  • @DoubleBob
    @DoubleBob Před 8 měsíci +86

    A great trick to make the next developer think far longer about a simple algorithm than necessary. It's like pranking your future self.

    • @mr.vladislav5746
      @mr.vladislav5746 Před 5 měsíci +14

      This is so elementary that even Sherlock Holmes wouldn't bother to investigate it.

    • @bitzero000
      @bitzero000 Před 5 měsíci +1

      did my future self forget how to read syntax

    • @DoubleBob
      @DoubleBob Před 5 měsíci +2

      @@bitzero000 If you think it's a good idea, then go ahead and see for yourself where it leads to. 🙂

    • @TechSupportDave
      @TechSupportDave Před 3 měsíci

      Or just don't forget python concepts 🤷

    • @rontheoracle
      @rontheoracle Před 2 měsíci +2

      @@DoubleBob It's like learning idiom on top of the previous old idiom, which is also on top of the previous previously old idiom.

  • @Tetrax
    @Tetrax Před 9 měsíci +25

    Cool I’m still gonna use the for loop

  • @TheMrCarnification
    @TheMrCarnification Před 8 měsíci +114

    No need to use sets, it's simpler and faster to:
    for key in loot:
    inv[key] = inv.get(key, 0) + loot[key]
    Do let me know if there are any problems with this

    • @char_noir
      @char_noir Před 7 měsíci +29

      And it should be faster, cause we got rid of union operator and conversion to set.

    • @megaing1322
      @megaing1322 Před 7 měsíci +27

      This modifies inv inplace instead of creating a new dictionary. However, I actually expect this to be the better behavior than what is shown in the short.
      A small thing to improve in your code is to use `for key, amount in loot.items()` instead of accessing `loot[key]` inside of the loop body.

    • @TheMrCarnification
      @TheMrCarnification Před 7 měsíci +2

      Right, I may have missed the point. Maybe they were trying to avoid using dict.copy().
      Is using .items() more time efficient? I didn't know that, thanks

    • @ahmadfahadhilyas
      @ahmadfahadhilyas Před 7 měsíci +5

      This raise problem when there is key in inv but not in loot.

    • @TheMrCarnification
      @TheMrCarnification Před 7 měsíci +10

      @@ahmadfahadhilyas no, it does not. Test it.

  • @Marco9603
    @Marco9603 Před 9 měsíci +2

    In Clojure you would do a much more simple `(merge-with + inv loot)`

  • @agnichatian
    @agnichatian Před 6 měsíci +3

    set(inv | loot) seems improper because if you try that type of expression by itself you will get undefined operation | for dict. In fact it doesn't work at all for me in python 3..8; did you change the code and not update the video ? I needed to do "set(inv.keys() | loot.keys())"

  • @andylovec8403
    @andylovec8403 Před 6 měsíci

    Loved this video. Thanks a lot!

  • @OctagonalSquare
    @OctagonalSquare Před 9 měsíci +2

    A neat use for dictionary comprehension! It’s something I’ve always known existed but never touched because I didn’t need it

  • @TechSupportDave
    @TechSupportDave Před 3 měsíci

    Turning my feed into programming stuff only les gooo

  • @Darkev77
    @Darkev77 Před 4 měsíci +1

    That’s great, but why the set operation?

  • @kalyaankumarsingh1318
    @kalyaankumarsingh1318 Před 8 měsíci +1

    I love ur short videos

  • @GeikoTreyarch
    @GeikoTreyarch Před dnem

    Your videos are so CRAZY EXCELLENT for us bro!! I enjoy and learn so much especially the ones you teach about GAMING RPG like this!!!! Like RPG codes like this is what made me subscribe and notifications+ on you hahaha😂

  • @sh4dowveil749
    @sh4dowveil749 Před 8 měsíci

    Its incredible reading comments on these videos and seeing everyone forget that your allowed to comment code to explain things

  • @fazfarren
    @fazfarren Před 10 měsíci +1

    Like the use of set to ensure you get the aggregate of both dictionaries in the output.

  • @talonhackbarth7652
    @talonhackbarth7652 Před 10 měsíci +60

    While I love the conciseness of this, I never end up using such complex comprehensions when writing code as it makes it virtually unreadable. While this only takes two lines, I would much prefer writing a for loop that would take six or seven that is easier on the eyes, lol.
    Keep up the great content

    • @theoebola2367
      @theoebola2367 Před 10 měsíci +9

      Im on the totally opposite side of the barricades here.
      I use comprehensions whenever possible instead of unnested loops.
      The readability is in the eye of the beholder, but i do enjoy turning 3 lines into one and avoiding extra indentations and that i never need to care about those k,v variables.

    • @ashersilver7388
      @ashersilver7388 Před 10 měsíci +3

      It makes more sense to write these in a helper function.

    • @evanbelcher
      @evanbelcher Před 7 měsíci +6

      No need for a loop or a helper function. Use Counter from collections, this problem has already been solved

    • @aaaabbbbbcccccc
      @aaaabbbbbcccccc Před 7 měsíci +2

      The simple solution you're advocating would be understood by any programmer. The pythonic solution is only understood by people who write python a lot.
      Keep writing code your way. The rest of us who haven't drunk the pythonic koolaid will thank you.

    • @franciscoflamenco
      @franciscoflamenco Před 7 měsíci +5

      That's a terrible take. Not only are comprehensions just as easy to understand (if not more) than for loops, but advocating for less "pythonic" solutions in deference to other programmers basically implies that all programming languages should be the same and that you should never learn anything new.

  • @SyberiaK
    @SyberiaK Před 10 měsíci +6

    If you are making an inventory - it might be better to iterate through loot only instead of your whole inventory

    • @exxology1
      @exxology1 Před 9 měsíci

      Can you explain through a code please?

    • @Zapnl
      @Zapnl Před 7 měsíci +2

      @@exxology1No need for a code
      Inventory may contain all keys in the game
      Loot will only contain a select few items, if it's referring to someone opening a container
      Therefore (except when inventory is empty), iterating over the loot object is always faster than iterating over the inventory

  • @AskAKill99
    @AskAKill99 Před 2 měsíci

    A cool way to extract quickly add the loot too your inv!

  • @John81oConnory
    @John81oConnory Před 2 měsíci

    Try a defaultDict from the collections module for the inventory!

  • @jm-lc3jp
    @jm-lc3jp Před 13 dny

    `from collections import Counter; Counter(inv) + Counter(loot)`

  • @rudra2036
    @rudra2036 Před 10 měsíci +32

    This man need a raise , keep high bruh ❤❤❤

  • @BogdanTestsSoftware
    @BogdanTestsSoftware Před 6 měsíci

    Set on dict keys - i didn't know that

  • @ruancomelli
    @ruancomelli Před 2 měsíci

    Or:
    from collections import Counter
    print(Counter(inv) + Counter(loot))

  • @Whatthetrash
    @Whatthetrash Před 10 měsíci

    This is very cool. Thanks for this. :)

  • @alfarisw
    @alfarisw Před 10 měsíci +20

    The backslash is not required between brackets

    • @insertcreativenamehere492
      @insertcreativenamehere492 Před 9 měsíci +1

      it is, because that is one expression split across multiple lines. Backslashes arent required when each line is one element in the dictionary

    • @schlopping
      @schlopping Před 9 měsíci +1

      ​@insertcreativenamehere492 it's not, try it for yourself. For example, this is perfectly valid:
      x = [
      i
      for i in range(10)
      if not i % 2
      ]
      You don't even need indentation if it's in a comprehension

    • @insertcreativenamehere492
      @insertcreativenamehere492 Před 9 měsíci +1

      @@schlopping my bad, I thought OP was talking about style guidelines. Yeah, that's technically valid code, but I would probably still add the backslashes for clarity

    • @schlopping
      @schlopping Před 9 měsíci +1

      @insertcreativenamehere492 Got it, thanks for clearing that up. Regardless I wouldn't add them since PEP-8 and most style guides heavily discourage backslashes, though as always, your personal preference is the most important

  • @LethalLuggage
    @LethalLuggage Před 6 měsíci

    I appreciate that none of this is really unique to python apart from the syntax being clean

  • @aidennelson3171
    @aidennelson3171 Před 9 měsíci +1

    May God bless, very nice and helpful reference!

  • @wagyumedia
    @wagyumedia Před měsícem

    Use Counter it’s fast too!

  • @M896
    @M896 Před 8 měsíci

    Would love to have all these examples in example scripts I just unzip on my raspberry pi to refer to as and when needed

  • @TheOnlyNightmare
    @TheOnlyNightmare Před 6 měsíci

    Use the counter from collections instead

  • @chedddargoblin
    @chedddargoblin Před 10 měsíci +41

    Wish i could bookmark this short

    • @smilyking6595
      @smilyking6595 Před 10 měsíci +7

      You can

    • @Oozy007
      @Oozy007 Před 10 měsíci +5

      you can save it bruh

    • @The.Truth13
      @The.Truth13 Před 10 měsíci +9

      I believe if you’re in a smartphone, the top right 3 vertical dots should allow you to save these shorts.

    • @exxology1
      @exxology1 Před 9 měsíci +7

      @@The.Truth13thank you!! Appreciate you for taking the extra minute to explain. I never realized I could save shorts either and I probably wouldn’t have bothered looking for how to lol

    • @The.Truth13
      @The.Truth13 Před 9 měsíci +3

      @@exxology1 it’s all good I gotcha💪🏽

  • @Faustollol
    @Faustollol Před 6 měsíci

    Thats why we have table.insert in lua. You can just do a for loop with all indexes of the lst and insert the value in it

  • @clusterbyte
    @clusterbyte Před 10 měsíci

    Really creative!! 👏

  • @BbB-vr9uh
    @BbB-vr9uh Před 5 měsíci

    Never knew about that union operation

  • @muhammadyasin2764
    @muhammadyasin2764 Před 9 měsíci +1

    Can anyone explain how the set(inv | loot) in the for-loop works?

    • @wrdsalad
      @wrdsalad Před 9 měsíci

      In his example, he uses set() to deduplicate the keys from inv and loot so they are only processed once.

  • @nopinias69
    @nopinias69 Před 10 měsíci

    This is very useful!!!
    Can you delve deeper into dict comprehension???
    I want to learn more about it

  • @erenc8377
    @erenc8377 Před 6 měsíci

    So, I want next video to be about dropping some items. 😂

  • @imyabota5785
    @imyabota5785 Před 7 měsíci

    As someone who peaked with writing a program which spits out the Fibonacci sequence in java script, cool.

  • @archniki_
    @archniki_ Před 7 měsíci

    Is there longer vid about it

  • @Matt-ct5ks
    @Matt-ct5ks Před 8 měsíci

    Could you declare the for loop before the k useage?

  • @Lion-wm6mf
    @Lion-wm6mf Před 9 měsíci

    Super cool, I would suggest maybe first storing the unique keys in a variable before the list comprehension rather than using set through each iteration

    • @mr.vladislav5746
      @mr.vladislav5746 Před 5 měsíci +1

      The set is only initialized once so no problem there 😀

  • @alex_nita
    @alex_nita Před měsícem +1

    Man this makes me miss php

  • @superboi
    @superboi Před 8 měsíci

    What if inv and loot are not listed in the same item order?

  • @kumaresanigator
    @kumaresanigator Před 9 měsíci +6

    Can we use conuter from collections ?

    • @luziferius3687
      @luziferius3687 Před 6 měsíci

      Yes. You can simply add two Counters together, and it'll do the multi-set merge for you.

  • @prashon10
    @prashon10 Před 3 měsíci

    bro, which font are you using?

  • @mannukhelega4806
    @mannukhelega4806 Před 3 měsíci

    Hey can you add captions somehow. I really love your videos but I am not good in English.

  • @asads30
    @asads30 Před 7 měsíci

    How about using reduce function

  • @owensayaman7047
    @owensayaman7047 Před 7 měsíci

    Sick!

  • @fatielfi239
    @fatielfi239 Před 5 měsíci

    4k in set(inv | loot
    😂😂

  • @aristekwawe3688
    @aristekwawe3688 Před 4 měsíci

    Hi what theme do you use ?

  • @abhijitnandy2401
    @abhijitnandy2401 Před 10 měsíci

    Could you please explain on k: ?

  • @Lion-wm6mf
    @Lion-wm6mf Před 9 měsíci

    I found another method using a loop and not creating a new dictionary:
    for key in dict2.keys():
    dict2[key] += dict1.get(key, 0)
    This will work only if you know the largest dictionary.

  • @prasadxev
    @prasadxev Před 10 měsíci

    How to convert date into string and retrieve back to date

  • @LifeExperimentalist
    @LifeExperimentalist Před 10 měsíci

    How does the text just come

  • @user-cx7pn4qi9h
    @user-cx7pn4qi9h Před 3 měsíci

    Bro which theme is this?

  • @wildfirewill
    @wildfirewill Před 6 měsíci

    Not a PyDev anymore but this is cool

  • @osquigene
    @osquigene Před 5 měsíci

    Or just use Counter, looks way better and can be used in many other places.
    from collections import Counter
    inventory = Counter(inv)
    inventory.update(loot)

  • @AbhishekGhosh-yb2nl
    @AbhishekGhosh-yb2nl Před 9 měsíci +1

    Awesome dude. Very useful 😊 especially in some django projects

  • @chriskeo392
    @chriskeo392 Před 10 měsíci +1

    Would like a slower video explaining this 😅

    • @_BoyDeveloper_
      @_BoyDeveloper_ Před 10 měsíci

      He really need to and take time to explain syntax to be understable easily

  • @d-aniel2388
    @d-aniel2388 Před 8 měsíci

    Whats that font?

  • @parassirohi8305
    @parassirohi8305 Před 10 měsíci

    How we do that without any inbuilt operator??

  • @LazyCorp-UwU
    @LazyCorp-UwU Před 9 měsíci

    seems like a java arraylist but with common property index?

  • @vijayakrishnak
    @vijayakrishnak Před 9 měsíci

    Which software do you use?

  • @DavidFonseca89
    @DavidFonseca89 Před 8 měsíci

    So cool 🔥🔥

  • @vibovitold
    @vibovitold Před 6 měsíci

    Kotlin version (just out of boredom):
    (inv.keys + loot.keys).associateWith { (inv[it] ?: 0) + (loot[it] ?: 0) }

  • @Bj-kl5vp
    @Bj-kl5vp Před 10 měsíci

    good stuff

  • @LimitedWard
    @LimitedWard Před 6 měsíci

    Feels inefficient compared to just iterating through one of the lists. May not matter if the dictionaries are small, but I wouldn't say this is particularly readable compared a for loop.

  • @uuu12343
    @uuu12343 Před 9 měsíci +2

    Couldnt you just create an empty dictionary then do a for loop through each dictionary and merge them together?

  • @user-dh8kb1tr5j
    @user-dh8kb1tr5j Před 7 měsíci

    how I can save mine of gold?

  • @RevibeMods
    @RevibeMods Před 8 měsíci

    How do you just paste the code like that?

  • @mdmaaz1355
    @mdmaaz1355 Před 6 měsíci

    Can anyone explain me how that happens pls im new to this

  • @aggi999
    @aggi999 Před 9 měsíci +1

    No, I'd rather just loop through the .keys() of each dictionary and use that to create a new one. It's more about readability and this method you're showing is not easy to read

  • @MrYbs-ie1jj
    @MrYbs-ie1jj Před 2 měsíci

    Whats a font?

  • @luziferius3687
    @luziferius3687 Před 6 měsíci +4

    from collections import Counter
    new_inv = Counter(inv) + Counter(loot)
    new_inv = dict(new_inv) # optional
    Done.

  • @anchalsharma0843
    @anchalsharma0843 Před 2 měsíci

    Dict/list comprehension are amazing ! Just be mindful of when to use them.Putting complex logic inside a comprehension makes the code less readable and hard to comprehend.
    (Think twice, if the logic that you are using to build the list/dict spans across multiple lines )

  • @mscout1
    @mscout1 Před 6 měsíci

    Just use collections.Counter.

  • @azim
    @azim Před 9 měsíci +7

    Why not use just Counter?

    • @nesletchimaew9209
      @nesletchimaew9209 Před 8 měsíci

      If you have a very large list that would be a performance issue

    • @cheaterman49
      @cheaterman49 Před 6 měsíci

      Came here for this. Nothing mind blowing about this video...

  • @nikschuetz4112
    @nikschuetz4112 Před 10 měsíci

    you don’t need a backslash

  • @robertmoss2692
    @robertmoss2692 Před 7 měsíci

    Julia can do this in a clean one-line: merge(+, inv, loot)
    You can use any function to apply to each duplicate (key, value) pair as the first argument

  • @maximoignacio6959
    @maximoignacio6959 Před 9 měsíci

    result = \
    {
    key: value + inv.get(key, 0)
    for key, value in loot.items()
    }

    • @rkdeshdeepak4131
      @rkdeshdeepak4131 Před 3 měsíci

      this will miss key that are in inv but not in loot

    • @maximoignacio6959
      @maximoignacio6959 Před 3 měsíci

      @@rkdeshdeepak4131 thanks for the comment a bit rusty on my python since I have not used it for years, had to solve this today thanks to you :D
      this will add regardless of how many items(keys) in both inv and loots are missing in each other.
      # dummy datas
      inv = {
      "Sword": 1,
      "Potion": 3,
      "Spear": 2,
      "Poison": 5,
      "Keys": 5,
      "Gears": 20,
      "medicine": 14
      }
      loot = {
      "Sword": 1,
      "Potion": 2,
      "Shield": 1,
      "Technology": 3,
      "Poison": 6,
      "Armaments": 14
      }
      # decorator
      def find_missing_keys(fn):
      def wrapper(inv, loot, *args, **kwargs) -> tuple:
      x, y = set(inv), set(loot)
      difference = tuple(x.difference(y))

      return fn(difference, *args, **kwargs)

      return wrapper
      # main func
      @find_missing_keys
      def combined_inventories(
      missing_keys: tuple,
      inv: dict = inv,
      loot: dict = loot
      ) -> dict:
      combined_dict = {}
      for item in missing_keys:
      if inv.get(item):
      new_item = inv.get(item)
      combined_dict[item] = new_item
      if loot.get(item):
      new_item = loot.get(item)
      combined_dict[item] = new_item
      res = { k: v + inv.get(k, 0) for k, v in loot.items() }

      combined_dict.update(res)
      return combined_dict

      print(combined_inventories(inv, loot))

  • @Sinke_100
    @Sinke_100 Před 10 měsíci +10

    You don't need to use set()
    How I would do it based on your style:
    merge = lambda x, y: {k:x.get(k, 0)+y.get(k,0) for k in x | y}
    inv = {'s':1,'p':2}
    chest = {'s':1,'p':3,'sh':1}
    inv = merge(inv, chest)
    print(inv)

    • @sergeiivanov5739
      @sergeiivanov5739 Před 9 měsíci

      And if ChainMap from collections suits this exercise??

    • @sergeiivanov5739
      @sergeiivanov5739 Před 9 měsíci

      @@blenderpanzi ChainMap is about another purpose, but still can be applied if you have more than 2 dictionaries. Your way of dictionary comprehension is appealing to me :)

    • @DietBroccoli
      @DietBroccoli Před 8 měsíci +1

      This violates PEP8.

  • @KlausbergerYT
    @KlausbergerYT Před 9 měsíci +24

    Nice to save some lines of code, but pythons main goal of readability is not achieved.

    • @ophello
      @ophello Před 7 měsíci +1

      That’s what comments are for!

    • @KlausbergerYT
      @KlausbergerYT Před 7 měsíci +5

      CZcams comments? Yes. Coding Comments? No. Code readability is not achieved by comments but by clear, structured and human-readable coding.

    • @PogoDigitalism
      @PogoDigitalism Před 7 měsíci +3

      Dictionary comprehension is also faster than regular loops.

    • @shrayesraman5192
      @shrayesraman5192 Před 7 měsíci +3

      @@PogoDigitalismi always say if you are that concerned about speed then python is not your language.

    • @PogoDigitalism
      @PogoDigitalism Před 7 měsíci

      @@shrayesraman5192 very true haha

  • @MichaelBeck_profile
    @MichaelBeck_profile Před 9 měsíci

    So it’s a for each?

  • @mrkike7343
    @mrkike7343 Před 10 měsíci

    May you live long.

  • @char_noir
    @char_noir Před 7 měsíci

    Union operator hurts

  • @jeromeevangelista7421
    @jeromeevangelista7421 Před 10 měsíci +1

    what's the "\" for?

    • @Bloooo95
      @Bloooo95 Před 10 měsíci

      Usually, it’s to say that the line continues to the next line. Here, it was completely unnecessary.

  • @ZantierTasa
    @ZantierTasa Před 9 měsíci

    huh, I had no idea "|" worked on dicts

  • @kareemosama7417
    @kareemosama7417 Před 8 měsíci

    A bit late but can someone explain the code to me a bit more? Especially the last part

  • @ratamat
    @ratamat Před 10 měsíci +1

    What is your vscode theme?????? I NEED to know

  • @auscompgeek
    @auscompgeek Před 9 měsíci

    or just update a collections.Counter

  • @vinayc.annangi
    @vinayc.annangi Před 7 měsíci

    Good one! How we can do the same with list of dictionaries.??

    • @rob011
      @rob011 Před 6 měsíci

      l = [{"a":1},{"b":2}]
      x = {k:v for d in l for k, v in d.items()}
      print(x)
      You can have multiple layers of unnesting in a comprehension like you would in a normal loop.

  • @michieleding1242
    @michieleding1242 Před 8 měsíci

    What python IDE are you using? Looks really clean. Wanne use it

  • @markusjohansson4949
    @markusjohansson4949 Před 8 měsíci

    Dict items

  • @moritz584
    @moritz584 Před 5 měsíci

    Tabs. Please.

  • @manjanjatx
    @manjanjatx Před 10 měsíci

    Why not just `combined = inv | loot`?