Python Forum
Python 2.7 Addition to dict is too slow
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python 2.7 Addition to dict is too slow
#4
Is this way faster?
from collections import defaultdict
struct = defaultdict(lambda: defaultdict(int))
struct['foo']['bar'] += 7
print(struct)
The following version probably works for every version of python since 1.0
def addBytesToStatStruct(struct, subscriberId, protocolId, octents):
    try:
        d = struct[subscriberId]
    except KeyError:
        struct[subscriberId] = {protocolId: octents}
        return
    try:
        d[protocolId] += octents
    except KeyError:
        d[protocolId] = octents
Other solutions involve setdefault() and get() as buran said.
Reply


Messages In This Thread
Python 2.7 Addition to dict is too slow - by VolanD - May-03-2018, 04:57 AM
RE: Python 2.7 Addition to dict is too slow - by Gribouillis - May-03-2018, 06:45 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Multiply and Addition in the same loop statement with logic. joelraj 2 1,115 Feb-02-2023, 04:33 AM
Last Post: deanhystad
  forloop to compute sum by alternating from addition to subtraction JulianZ 3 1,922 Apr-02-2022, 09:36 AM
Last Post: DeaD_EyE
  My python code is running very slow on millions of records shantanu97 7 2,712 Dec-28-2021, 11:02 AM
Last Post: Larz60+
  String index out of bounds ( Python : Dict ) kommu 2 2,482 Jun-25-2020, 08:52 PM
Last Post: menator01
  Python 2 to 3 dict sorting joshuaprocious 2 69,747 May-14-2020, 03:28 PM
Last Post: joshuaprocious
  Sort a dict in dict cherry_cherry 4 90,049 Apr-08-2020, 12:25 PM
Last Post: perfringo
  Python list - group by dict key karthidec 2 9,546 Nov-25-2019, 06:58 AM
Last Post: buran
  addition for elements in lists of list ridgerunnersjw 3 3,191 Sep-15-2019, 07:11 AM
Last Post: perfringo
  multiplication by successive addition Zebrol 1 3,600 Sep-14-2019, 05:37 PM
Last Post: ichabod801
  Slow Python Code Jay123 3 2,596 Sep-09-2019, 08:46 AM
Last Post: Jay123

Forum Jump:

User Panel Messages

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