I have string like below:
data = """
ID: ID/123456-00000003c
Value2: 1382386949.12
Value3: 00420903237127
Value4: 21
ID: ID/654431-0000000a
Value2: 1382386943.1032
Value3: 004989353474713
Value4: 33"""
Every variable is in separate line in shape:
variable: value
I want to make a function to get list of values of variable. Something like this:
def get_values_of( variable_name ):
code....
return variable_list
if I call this function like this:
get_values_of(ID)
it return list of values of variable "ID":
variables = ['ID/123456-00000003c', 'ID/654431-0000000a']
or
get_values_of(Value2)
it return
variables = ['1382386949.12', '1382386943.1032']
Please, what is the best way to do this?
-
You can split the strings.aIKid– aIKid2013年10月23日 07:43:03 +00:00Commented Oct 23, 2013 at 7:43
2 Answers 2
data = """
ID: ID/123456-00000003c
Value2: 1382386949.12
Value3: 00420903237127
Value4: 21
ID: ID/654431-0000000a
Value2: 1382386943.1032
Value3: 004989353474713
Value4: 33"""
myData = {}
for line in data.split("\n"):
if line:
key, value = line.split(": ")
myData.setdefault(key, [])
myData[key].append(value)
def get_values_of(actualKey):
return myData[actualKey]
print get_values_of("ID")
print get_values_of("Value2")
print get_values_of("Value3")
print get_values_of("Value4")
Output
['ID/123456-00000003c', 'ID/654431-0000000a']
['1382386949.12', '1382386943.1032']
['00420903237127', '004989353474713']
['21', '33']
1 Comment
defaultdict here.This code should help you get started.
data = """
ID: ID/123456-00000003c
Value2: 1382386949.12
Value3: 00420903237127
Value4: 21
ID: ID/654431-0000000a
Value2: 1382386943.1032
Value3: 004989353474713
Value4: 33"""
for line in data.splitlines():
if not line: # skips empty lines that would otherwise cause errors
continue
key, value = line.split(': ')
print 'key: {}, value: {}'.format(key, value)
Output:
>>>
key: ID, value: ID/123456-00000003c
key: Value2, value: 1382386949.12
key: Value3, value: 00420903237127
key: Value4, value: 21
key: ID, value: ID/654431-0000000a
key: Value2, value: 1382386943.1032
key: Value3, value: 004989353474713
key: Value4, value: 33
Basically, you are iterating over each line, then split the line at the : to get the key and the value. You can create dictionaries for each segment, or do whatever you want by checking what the key is over each iteration. Your choice. This code is here to help guide you and give you a push in the right direction.
A sample of what you wanted:
def get_vars(data, var):
return [line.split(': ')[1] for line in data.splitlines() if line and line.startswith(var)]
>>>print get_vars(data, 'ID')
['ID/123456-00000003c', 'ID/654431-0000000a']
1 Comment
not line, as many don't know what you can actually do that with empty strings.