473,657 Members | 2,376 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

shelve and nested dictionaries

I'm a newbie to Python, with some experience using perl (where I used
nested arrays and hashes extensively). I am building a script in
python for a MUD I play, and I want to use the shelve module to store
persistent information between script executions. The following code
does not work for me,

import shelve, sys, os, string
db = shelve.open(os. path.abspath(os .path.dirname(s ys.argv[0])) + '/' +
'sandbox.dat', 'c')
db['JustSomeVariab le'] = 'apple'
db['subdb'] = {}
db['subdb']['anotherdict'] = {}
db['subdb']['anotherdict']['bleh'] = 'hello world'
db.close()

of course, that's just a working example but it illustrates the
problem i'm having. I think shelve objects act like dictionaries in a
way, at least they seem to have dictionary keys beneath them. And I
don't seem to have this problem when I use a normal dictionary as
opposed to shelve for nesting other dictionaries.

So i'm now confused, i've hit a brick wall and i'm not sure how to
solve this problem.

Can anyone explain what i'm doing wrong?

Thanks
Jan 3 '08 #1
1 4573
Matthew Schibler wrote:
I'm a newbie to Python, with some experience using perl (where I used
nested arrays and hashes extensively). I am building a script in
python for a MUD I play, and I want to use the shelve module to store
persistent information between script executions. The following code
does not work for me,

import shelve, sys, os, string
db = shelve.open(os. path.abspath(os .path.dirname(s ys.argv[0])) + '/' +
'sandbox.dat', 'c')
db['JustSomeVariab le'] = 'apple'
db['subdb'] = {}
db['subdb']['anotherdict'] = {}
db['subdb']['anotherdict']['bleh'] = 'hello world'
db.close()

of course, that's just a working example but it illustrates the
problem i'm having. I think shelve objects act like dictionaries in a
way, at least they seem to have dictionary keys beneath them.
the shelve module only tracks changes to the shelf itself (i.e.
db[key]), not changes to to mutable objects stored in the shelve).

to change a mutable object, you have to fetch it, modify it, and then
write it back:

value = db[key]
... update value ...
db[key] = value

in Python 2.3 and later, the shelve can help you with this, to some
extent; from the help page:

To avoid the problem with mutable entries, you may pass
the keyword argument writeback=True in the call to
shelve.open. When you use:

d = shelve.open(fil ename, writeback=True)

then d keeps a cache of all entries you access, and writes
them all back to the persistent mapping when you call
d.close(). This ensures that such usage as
d[key].append(anitem) works as intended.

However, using keyword argument writeback=True may consume
vast amount of memory for the cache, and it may make
d.close() very slow, if you access many of d's entries
after opening it in this way: d has no way to check which
of the entries you access are mutable and/or which ones
you actually mutate, so it must cache, and write back at
close, all of the entries that you access. You can call
d.sync() to write back all the entries in the cache, and
empty the cache (d.sync() also synchronizes the persistent
dictionary on disk, if feasible).

</F>

Jan 3 '08 #2

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

Similar topics

6
4741
by: Rami A. Kishek | last post by:
Hi - this mysterious behavior with shelve is just about to kill me. I hope someone here can shed some light. First of all, I have this piece of code which uses shelve to save instances of some class I define. It works perfectly on an old machine (PII-400) running Python 2.2.1 under RedHat Linux 8.0. When I try to run it under Python for windows ME on a P-4 1.4 GHz, however, it keeps crashing on reading from the shelved file the second...
1
6722
by: Kris Caselden | last post by:
Python's docs say that Shelve uses Pickle to serialize its data. However, I've noticed that Pickle can maintain internal links, while Shelve cannot. For instance: >>> d = shelve.open('shelvedata.txt',writeback=True) >>> d= >>> d=d >>> print d {'a': , 'b': } >>> d=2 >>> print d {'a': , 'b': }
0
2462
by: seth | last post by:
Last week I encountered an AttributeError in my unit tests that I wasn'table to catch with an "except AttributeError" statement. The problem stemmed from a class that raised an error inside __init__and defined a __del__ method to clean up resources. I then discovered asimilar problem in the shelve module. This led me to two importantdiscoveries: 1. Attributes defined in __init__ after an error is raised will not be apart of the...
2
1569
by: Amir Michail | last post by:
Hi, Is there a program for editing shelve databases? Amir
4
2333
by: Terry Hancock | last post by:
I only just recently had a look at the shelve module, and it looks pretty handy, my only question being, what if I really want two shelves? Must I use two files? Also, it seems strange that shelve only works with filenames. I would've expected there to at least be a variant that would put a shelve database on a file that is opened for read/write (that is a file object). That would be handy if, for example, I wanted to couple
2
2011
by: techiepundit | last post by:
I'm parsing some data of the form: OuterName1 InnerName1=5,InnerName2=7,InnerName3=34; OuterName2 InnerNameX=43,InnerNameY=67,InnerName3=21; OuterName3 .... and so on.... These are fake names I've made up to illustrate the point more clearly. (the embedded device device can't produce XML and this is what I have
3
7829
by: Michele Petrazzo | last post by:
Hi, I'm trying a script on a debian 3.1 that has problems on shelve library. The same script work well on a fedora 2 and I don't know why it create this problem on debian: #extract from my code import shelve class XX: def __init__(self): self._data = shelve.open("/tmp/myfile")
13
6493
by: 7stud | last post by:
test1.py: -------------------- import shelve s = shelve.open("/Users/me/2testing/dir1/aaa.txt") s = "red" s.close() --------output:------ $ python test1.py
5
1643
by: gluckj | last post by:
Hi, I'm not a Win ME fan myself (I'm a Mac user), but I'm here in Thailand developing software for special-needs kids, and the test PC in my home office is a Win ME machine (sigh). So when I ported my Python program today to the PC, it quickly crashed. Everything seems to work except for shelve. Using the latest version of Python (2.5.1), when I do the following in IDLE on the Win ME machine here's the result: Python 2.5.1...
0
8827
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
8732
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8504
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8606
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
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4159
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
4318
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1959
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1622
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.