473,789 Members | 2,422 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Naming dictionaries recursively

TYR
I'd like to do something like this; iterate through a file which
consists of data stored in dictionary format, one dict on each line,
and read each line into a new dict using one of the values in the dict
as its name...

for example:

stuff = open('data.txt' )
for eachLine in stuff:
name{}
name = eachLine
.....and then do something clever to extract the value of the key
(name) from the line and use it as the dictionary's name.

A line from data.txt would look like this: {'name' : Bob, 'species' :
Humboldt, 'colour' : red, 'habits' : predatory}. Aim is to call one of
them by name, and merge the values in that dictionary into a string
pulled from another source.

Aug 17 '07 #1
7 1386
On Aug 17, 7:38 am, TYR <a.harrow...@gm ail.comwrote:
I'd like to do something like this; iterate through a file which
consists of data stored in dictionary format, one dict on each line,
and read each line into a new dict using one of the values in the dict
as its name...

for example:

stuff = open('data.txt' )
for eachLine in stuff:
name{}
name = eachLine
....and then do something clever to extract the value of the key
(name) from the line and use it as the dictionary's name.

A line from data.txt would look like this: {'name' : Bob, 'species' :
Humboldt, 'colour' : red, 'habits' : predatory}. Aim is to call one of
them by name, and merge the values in that dictionary into a string
pulled from another source.
I'm not sure I follow exactly what you want to do, but you can always
use eval for each line in that file.

But, if the line you provided for testing is one that actually comes
from the file, you'll have to patch it before you eval the line. I
think this regexp will work. Be careful though, it assumes that all
values are whole words, that is they don't have spaces in them.

# This is far from ideal, but you get what you pay for :).
re.sub(r':\s*(\ w+)(,|})', r"': '\1'\2", line)

Anyway, after you've cleaned up your input line this ought to work:
d = eval(line)

Also, if you're building the input file from within a python program,
maybe you should consider the pickle module.

That ought to give you a good start...

jw

Aug 17 '07 #2
On Fri, 17 Aug 2007 12:38:16 +0000, TYR wrote:
I'd like to do something like this; iterate through a file which
consists of data stored in dictionary format, one dict on each line,
and read each line into a new dict using one of the values in the dict
as its name...
Store the dictionaries in a dictionary with that value as key.
A line from data.txt would look like this: {'name' : Bob, 'species' :
Humboldt, 'colour' : red, 'habits' : predatory}. Aim is to call one of
them by name, and merge the values in that dictionary into a string
pulled from another source.
So the tougher problem seems to be parsing those lines. That is not a
valid Python dictionary unless the names `Bob`, `Humboldt`, `red`, and
`predatory` are not already defined. So you can't just ``eval`` it.

Ciao,
Marc 'BlackJack' Rintsch
Aug 17 '07 #3
TYR
So the tougher problem seems to be parsing those lines. That is not a
valid Python dictionary unless the names `Bob`, `Humboldt`, `red`, and
`predatory` are not already defined. So you can't just ``eval`` it.
In what way? {'key': val}, right?

Anyway, I can always change the format they go into the file in.


Aug 17 '07 #4
On Aug 17, 7:38 am, TYR <a.harrow...@gm ail.comwrote:
I'd like to do something like this; iterate through a file which
consists of data stored in dictionary format, one dict on each line,
and read each line into a new dict using one of the values in the dict
as its name...

for example:

stuff = open('data.txt' )
for eachLine in stuff:
name{}
name = eachLine
....and then do something clever to extract the value of the key
(name) from the line and use it as the dictionary's name.

A line from data.txt would look like this: {'name' : Bob, 'species' :
Humboldt, 'colour' : red, 'habits' : predatory}. Aim is to call one of
them by name, and merge the values in that dictionary into a string
pulled from another source.
Pyparsing includes an example that is very similar to this. Here is
that example adapted to your specific data:

from pyparsing import *

line = """{'name' : Bob, 'species' : Humboldt, 'colour' : red,
'habits' : predatory}"""

LBRACE,RBRACE,C OLON,COMMA = map(Suppress,"{ }:,")
key = sglQuotedString .setParseAction (removeQuotes)
value = OneOrMore(Word( alphanums))\
.setParseAction (keepOriginalTe xt)
entry = Group(key + COLON + empty + value)
lineExpr = LBRACE + Dict(delimitedL ist(entry)) + RBRACE

parsedData = lineExpr.parseS tring(line)

# some examples of accessing the parsed data
print "Keys:", parsedData.keys ()
print parsedData.name
print parsedData.colo ur
print "Name: %(name)s \nSpecies: %(species)s \n" \
"Colour: %(colour)s \nHabits: %(habits)s" % parsedData

Prints:

Keys: ['colour', 'habits', 'name', 'species']
Bob
red
Name: Bob
Species: Humboldt
Colour: red
Habits: predatory

-- Paul

Aug 17 '07 #5
On Aug 17, 3:43 pm, TYR <a.harrow...@gm ail.comwrote:
So the tougher problem seems to be parsing those lines. That is not a
valid Python dictionary unless the names `Bob`, `Humboldt`, `red`, and
`predatory` are not already defined. So you can't just ``eval`` it.

In what way? {'key': val}, right?

Anyway, I can always change the format they go into the file in.
If you control the file format then you could create a valid python
list of dictionaries as the intermediate file format. Something like:

data = [
{'name' : 'Bob', 'species' : 'Humboldt', 'colour' : 'red',
'habits' : 'predatory'},
{ ... },
...
}

You can then name the file with a .py ending and import it as a list
of dictionaries that you can then process to form a dict of dicts:

datadict = dict( (data2name(d), d) for d in modulename.data )

- Paddy.

Aug 17 '07 #6
TYR
That sounds like a solution. I think the core of the question is as
follows; if I was to call the dict() function for each line, thus
creating a dictionary, and then rename it to dict['name'], will there
be a namespace collision on the next loop when dict() is called again?
Obviously the first dictionary will still be there, as it still has a
refcount of 1; but if it gets overwritten, will the object that the
new name refers to be overwritten too?

Aug 18 '07 #7
On Aug 18, 11:44 am, TYR <a.harrow...@gm ail.comwrote:
That sounds like a solution. I think the core of the question is as
follows; if I was to call the dict() function for each line, thus
creating a dictionary, and then rename it to dict['name'], will there
be a namespace collision on the next loop when dict() is called again?
Obviously the first dictionary will still be there, as it still has a
refcount of 1; but if it gets overwritten, will the object that the
new name refers to be overwritten too?
if data2name might give colliding names then you could use tuples as
dictionary keys as shown below:

import modulename
datadict = dict( ((data2name(d), count), d)
for count,d in enumerate(modul ename.data) )

Generally, if you try and create two keys with the same name in a
dictionary, they will clash and only the second value is retained.

- Paddy.

Aug 18 '07 #8

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

Similar topics

0
1367
by: Till Plewe | last post by:
Is there a way to speed up killing python from within a python program? Sometimes shutting down takes more than 10 times as much time as the actual running of the program. The programs are fairly simple (searching/organizing large boardgame databases) but use a lot of memory (1-6GB). The memory is mostly used for simple structures like trees or relations. Typically there will be a few large dictionaries and many small...
8
2624
by: Frohnhofer, James | last post by:
My initial problem was to initialize a bunch of dictionaries at the start of a function. I did not want to do def fn(): a = {} b = {} c = {} . . . z = {}
3
2377
by: Shivram U | last post by:
Hi, I want to store dictionaries on disk. I had a look at a few modules like bsddb, shelve etc. However would it be possible for me to do the following hash = where the key is an int and not a string bsddb requires that both the key,value are string. shelve does support values being object but not the keys. Is there any
8
6679
by: beliavsky | last post by:
Since Python does not have declarations, I wonder if people think it is good to name function arguments according to the type of data structure expected, with names like "xlist" or "xdict".
210
10560
by: Christoph Zwerschke | last post by:
This is probably a FAQ, but I dare to ask it nevertheless since I haven't found a satisfying answer yet: Why isn't there an "ordered dictionary" class at least in the standard list? Time and again I am missing that feature. Maybe there is something wrong with my programming style, but I rather think it is generally useful. I fully agree with the following posting where somebody complains why so very basic and useful things are not part...
5
7812
by: aurora00 | last post by:
I use generators a lot. E.g. def gen_words(text) ... parse text ... yield each word in text for word in gen_words(text): print word
23
2444
by: Thorsten Kampe | last post by:
Okay, I hear you saying 'not another naming conventions thread'. I've read through Google and the 'naming conventions' threads were rather *spelling conventions* threads. I'm not interested in camelCase versus camel_case or anything mentioned in 'PEP 8 -- Style Guide for Python Code'. What I'm looking for is hints or ideas how to name your variables and especially how to name functions, methods and classes.
0
1837
by: d80013 | last post by:
Hello all, I am trying to create a Dictionary of dictionaries in VBA. All I do is declare two dictionaries, one temporary one, and add the temporary dictionary to the main one recursively. The dictionaries are created fine, and i can access their values without any problems. What I want to do however is to pass the (low-level) dictionary to a function and have it access its data. But I can't seem to be able to do that. I have tried...
14
1824
by: cnb | last post by:
Are dictionaries the same as hashtables?
0
10404
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
10195
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...
0
9979
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
9016
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7525
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5415
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
5548
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4090
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
3
2906
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.