Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
duplicate key storing
#1
i recall a module that did this, but i haven't gone to look for it, yet. i think it was called collection. i want to stored keyed data which could have multiple data objects under the same key. what i would normally do is just keep everything in a list, with all lists in a dictionary under the respective key, and append if the list is already there. that way i have every object that has that key and they are in the order stored (i don't need the ordering). right now i am wondering if my simple way is good enough or if i should go find that module.
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
Here's the documentation for collections. Does anything sound suitable?
I am trying to help you, really, even if it doesn't always seem that way
Reply
#3
Sound like defaultdict with list.
>>> from collections import defaultdict
>>> 
>>> d = defaultdict(list)
>>> s = [('green', 1), ('blue', 25), ('green', 100), ('blue', 4), ('red', 1)]
>>> for k, v in s:
...     d[k].append(v)
...     
>>> d.items()
dict_items([('green', [1, 100]), ('blue', [25, 4]), ('red', [1])])
Reply
#4
I never used it, but the interface seems to be very easy:

import multidict


md = multidict.MultiDict()
md['foo'] = 1337
md.add('foo', 42)
print(md.getall('foo'))
Output:
[1337, 42]
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
i think i was thinking about collections.Counter when i was thinking there was a way to work with multiple things with the same key.

i don't think defaultdict will help much since a list in a regular dictionary can accomplish this,

but multidict might be the thing. any documentation on multidict? i am wondering if md.add('foo',42) depends on 'foo' already being in there ... iow, do i have to do md['foo'] the first time. or was that coded just to show it could be added either way? maybe doing 2 one way and 2 the other way would show. will there be 4 instances of 'foo' keys in md?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Taking user input and storing that to a variable then storing that variable to a list jowalk 12 37,243 Mar-27-2017, 11:45 PM
Last Post: wavic

Forum Jump:

User Panel Messages

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