473,717 Members | 2,039 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

creating and appending to a dictionary of a list of lists

Hey,

I started with this:

factByClass = {}

def update(key, x0, x1, x2, x3):
x = factByClass.set default(key, [ [], [], [], [] ])
x[0].append(x0)
x[1].append(x1)
x[2].append(x2)
x[3].append(x3)

update('one', 1, 2, 3, 4)
update('one', 5, 6, 7, 8)
update('two', 9, 10, 11, 12)

print factByClass

{'two': [[9], [10], [11], [12]], 'one': [[1, 5], [2, 6], [3, 7], [4,
8]]}

I then 'upgraded' to this:

def update(key, *args):
x = factByClass.set default(key, [[], [], [], [] ])
for i, v in enumerate(args) :
x[i].append(v)

Is there a better way?
Cheers!

Aug 15 '07 #1
2 3632
Ant
On Aug 15, 3:30 am, pyscottish...@h otmail.com wrote:
Hey,

I started with this:

factByClass = {}
....
def update(key, *args):
x = factByClass.set default(key, [[], [], [], [] ])
for i, v in enumerate(args) :
x[i].append(v)

Is there a better way?
Well, the following is perhaps neater:
>>factByClass = defaultdict(lam bda: [[],[],[],[]])
def update(key, *args):
.... map(list.append , factByClass[key], args)
....
>>update('one ', 1, 2, 3, 4)
update('one ', 5, 6, 7, 8)
update('two ', 9, 10, 11, 12)

print factByClass
defaultdict(<fu nction <lambdaat 0x00F73430>, {'two': [[9], [1
0], [11], [12]], 'one': [[1, 5], [2, 6], [3, 7], [4, 8]]})

It abuses the fact that list.append modifies the list in place -
normally you would use map to get a new list object. In this case the
new list returned by map is just a list of None's (since append
returns None - a common idiom for functions that operate by side
effect), and so is not used directly.

--
Ant...

http://antroy.blogspot.com/

Aug 15 '07 #2
On Aug 15, 8:08 am, Ant <ant...@gmail.c omwrote:
On Aug 15, 3:30 am, pyscottish...@h otmail.com wrote:
Hey,
I started with this:
factByClass = {}

...
def update(key, *args):
x = factByClass.set default(key, [[], [], [], [] ])
for i, v in enumerate(args) :
x[i].append(v)
Is there a better way?

Well, the following is perhaps neater:
>factByClass = defaultdict(lam bda: [[],[],[],[]])
def update(key, *args):

... map(list.append , factByClass[key], args)
...>>update('on e', 1, 2, 3, 4)
>update('one' , 5, 6, 7, 8)
update('two' , 9, 10, 11, 12)
>print factByClass

defaultdict(<fu nction <lambdaat 0x00F73430>, {'two': [[9], [1
0], [11], [12]], 'one': [[1, 5], [2, 6], [3, 7], [4, 8]]})

It abuses the fact that list.append modifies the list in place -
normally you would use map to get a new list object. In this case the
new list returned by map is just a list of None's (since append
returns None - a common idiom for functions that operate by side
effect), and so is not used directly.

--
Ant...

http://antroy.blogspot.com/
Nice. I like it. Thanks a lot!

Aug 15 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
2628
by: Andy C | last post by:
I am new to python, so please bear with me if I am making some conceptual error. Basically I want to create a graph with an adjacency list representation, but I don't want any of the adjacency lists to have duplicate strings when it is avoidable. I have a function createEdge that adds an edge to the graph. The arguments will be distinct since they are read from text files. But basically I want to use the dictionary as a string pool,...
2
6581
by: John Mudd | last post by:
I must be missing something here. It's clearly faster to lookup an item directly in a dictionary than to scan through a list. So when I have a large lookup table I always load it in the form of a dictionary. But it seems a waste. I end up having to assign an artificial value to the dictionary entry. Below I assign the value "None" to each dictionary entry. Is there a better way? I feel like I'm misusing the dictionary.
23
40633
by: Fuzzyman | last post by:
Pythons internal 'pointers' system is certainly causing me a few headaches..... When I want to copy the contents of a variable I find it impossible to know whether I've copied the contents *or* just created a new pointer to the original value.... For example I wanted to initialize a list of empty lists.... a=, , , , ] I thought there has to be a *really* easy way of doing it - after a
4
3200
by: bucket79 | last post by:
Hi is there anyway appending to dictionary? list has this feature >>>a = >>>a.append(1) >>>print a but dictionary can't
11
6078
by: Girish Sahani | last post by:
I wrote the following code to concatenate every 2 keys of a dictionary and their corresponding values. e.g if i have tiDict1 = tiDict1 = {'a':,'b':} i should get tiDict2={'ab':} and similarly for dicts with larger no. of features. Now i want to check each pair to see if they are connected...element of this pair will be one from the first list and one from the second....e.g for 'ab' i want to check if 1 and 3 are connected,then 1 and...
14
3463
by: vatamane | last post by:
This has been bothering me for a while. Just want to find out if it just me or perhaps others have thought of this too: Why shouldn't the keyset of a dictionary be represented as a set instead of a list? I know that sets were introduced a lot later and lists/dictionaries were used instead but I think "the only correct way" now is for the dictionary keys and values to be sets. Presently {1:0,2:0,3:0}.keys() will produce but it could also...
10
2331
by: Ben | last post by:
Hello... I have set up a dictionary into whose values I am putting a list. I loop around and around filling my list each time with new values, then dumping this list into the dictionary. Or so I thought... It would appear that what I am dumping into the dictionary value is only a pointer to the original list, so after all my iterations all I have is a dictionary whose every value is equal to that of the list the final time I looped...
1
2540
by: Eran | last post by:
Hi, I have a huge data structure, which I previosly stored in a Dictionary<int, MyObj> MyObj is relatively small (2 int, 1 DateTime, 1 bool). The dictionary I am using is quite large (25,000), and I have 500 such dictionaries. What I've noticed is that the total memory consumed became over 1 GB. When I changed the implementation to List<MyObj>, or SortedList<int,
19
8609
by: Dr Mephesto | last post by:
Hi! I would like to create a pretty big list of lists; a list 3,000,000 long, each entry containing 5 empty lists. My application will append data each of the 5 sublists, so they will be of varying lengths (so no arrays!). Does anyone know the most efficient way to do this? I have tried: list = ,,,,] for _ in xrange(3000000)]
0
8823
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
8719
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9348
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9048
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4478
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4739
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3177
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2545
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2120
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.