473,394 Members | 1,734 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

How to retrieve key value pairs in python

3
Hi,
Iam new to python.

I have a config file as shown below in the same order .I need to retrieve key value pairs from config file and will use those values in my script


# Name and details
(
{ group => 'abc',
host => 'pqr.com',
user => 'anonymous',
src => '/var/tmp',
dest => '/tmp',
},
{group => 'abc',
host =>'pqr.com',
user => 'anonymous',
src => '/tmp'
dest => '/var/tmp'
},
{ group => 'pqr',
host =>'abc.com',
user => 'xyz',
src => '/home/pp',
dest => '/var/tmp',
},
{ group => 'xyz',
host =>'p.com',
user => 'x',
src => '/home/',
dest => '/tmp',
}
)

Each {
},is considerd as one block..Group,user,host are unique as well as repeated.

I have to read and parse the config file and display key and value pair.Pls help.

Key : group,Value : 'abc'(say)
key : host ,Value :'pqr.com'
Key : user, Value :'anonymous'
Key : src,Value :'/var/tmp',
key : dest,Value : '/tmp'


Thank you,
Apr 27 '12 #1

✓ answered by bvdet

Your data is misconfigured because of some missing commas. Assuming you add in the missing commas, a list of dictionaries could be compiled. You can use string method index, and string slicing in a while loop to compile the list. Enclose the index call in a try/except block, because index will raise a ValueError if no substring is found. Example where config is the full configuration string read from the file:
Expand|Select|Wrap|Line Numbers
  1. idx = 0
  2. dictList = []
  3. while True:
  4.     try:
  5.         start = config.index("{", idx)
  6.         end = config.index("}", start+1)
  7.         slice = config[start+1:end-1]
  8.         sliceList = [s.strip() for s in slice.split(",") if s.strip()]
  9.         dd = {}
  10.         for item in sliceList:
  11.             key, value = [s.strip() for s in item.split("=>")]
  12.             dd[key] = value
  13.         dictList.append(dd)
  14.         idx = end+1
  15.     except ValueError, e:
  16.         break
Would it not be better to use XML for your configuration data?

4 5997
bvdet
2,851 Expert Mod 2GB
Your data is misconfigured because of some missing commas. Assuming you add in the missing commas, a list of dictionaries could be compiled. You can use string method index, and string slicing in a while loop to compile the list. Enclose the index call in a try/except block, because index will raise a ValueError if no substring is found. Example where config is the full configuration string read from the file:
Expand|Select|Wrap|Line Numbers
  1. idx = 0
  2. dictList = []
  3. while True:
  4.     try:
  5.         start = config.index("{", idx)
  6.         end = config.index("}", start+1)
  7.         slice = config[start+1:end-1]
  8.         sliceList = [s.strip() for s in slice.split(",") if s.strip()]
  9.         dd = {}
  10.         for item in sliceList:
  11.             key, value = [s.strip() for s in item.split("=>")]
  12.             dd[key] = value
  13.         dictList.append(dd)
  14.         idx = end+1
  15.     except ValueError, e:
  16.         break
Would it not be better to use XML for your configuration data?
Apr 29 '12 #2
sa537
3
Thanks for your respons.It helped me a lot.No i cant use any xml file..
I did in perl as below (sample code)
Expand|Select|Wrap|Line Numbers
  1. "eval /@temp" =@configfile
  2. for $job in @temp
  3.   for $jobdef in %$job
  4.     $jobdef -> {src} = '/tmp'
  5.     $jobdef -> {user} = x
Is there any way to do similar to this in python?

Thank you in advance
May 1 '12 #3
bvdet
2,851 Expert Mod 2GB
Since I don't know Perl, I can't help with "similar" code. I mentioned XML because your data would be ideal for it, and you can use an XML parser to get the data.
May 1 '12 #4
sa537
3
Thanks for ur response again..Well,its a CSV file...I cant put the data in XML...Tried ur code,worked something well...Hw to print values associated with user,source,group,host,dest... pertaining to a single block {
}
...?
May 2 '12 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: Equis Uno | last post by:
Hi, Assume I'm given a 100k file full of key-value pairs: date,value 26-Feb-04,36.47 25-Feb-04,36.43 24-Feb-04,36.30 23-Feb-04,37.00 20-Feb-04,37.00
4
by: Bill | last post by:
If, for example, I retrieve a connectionstring from a config file using something like: Value = ConfigurationSettings.AppSettings; This will return a string that is semi-colon delimited. If I...
3
by: He Shiming | last post by:
Hi Folks, Happy holidays! I have a question regarding STL multimap. Basically, the current multimap<int,int> look like this: key=>value 1=>10, 1=>20, 1=>30,
3
by: Diffident | last post by:
Hello All, I want to display all the name-value pairs of the session object....how can I print them out? i.e., suppose once a user logs in I set a session variable login time Session = "2pm" and...
13
by: Markus Dehmann | last post by:
I have key-value pairs where the key consists of 3 integers, the value is a double. I am wondering what's the best way to store them (preferrably in an STL container). A fast lookup should be...
7
by: esj | last post by:
let me say up front that my experience with JavaScript and "Ajax" interactions has been horrific. There are weeks I will never get back because of it. Whenever I encounter something so horrific...
6
by: Evyn | last post by:
Hi, How do I compare 2 maps for identical keys, and if they have identical keys, check if they have identical values? In either case I want to copy ONLY that key value pair to one of two...
0
by: =?Utf-8?B?SGVucnlDQw==?= | last post by:
We are trying to develop a set of C# 2.0 web services that are data driven, loosely coupled, easy to maintain, and somewhat high preferment (I'm sure that's either an oxymoron or everyone else's...
4
RedSon
by: RedSon | last post by:
Give this XML: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <linear xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <linedata> <line> <rise>253</rise>...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...
0
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...
0
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...
0
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...

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.