在python中聚合键值对

时间:2013-06-10 23:10:00

标签: python key-value aggregation

我有一个与python代码有关的问题。 如果key = kv1,我需要聚合,我该怎么做?

input='num=123-456-7890&kv=1&kv2=12&kv3=0'
result={}
for pair in input.split('&'):
(key,value) = pair.split('=')
if key in 'kv1':
   print value
   result[key] += int(value)
print result['kv1']

非常感谢!!

3 个答案:

答案 0 :(得分:2)

我假设你的意思是key == 'kv1'而且kv中的input原来是kv1result是空的dictresult[key] += int(value)

不需要result[key] = int(value)
input = 'num=123-456-7890&kv1=1&kv2=12&kv3=0'
keys = {k: v for k, v in [i.split('=') for i in input.split('&')]}

print keys # {'num': '123-456-7890', 'kv2': '12', 'kv1': '1', 'kv3': '0'}

result = {}
for key, value in keys.items():
    if key == 'kv1':

        # if you need to increase result['kv1']
        _value = result[key] + int(value) if key in result else int(value)
        result[key] = _value

        # if you need to set result['kv1']
        result[key] = int(value)

print result # {'kv1': 1}

假设您有多行数据包含:

num=123-456-7890&kv1=2&kv2=12&kv3=0
num=123-456-7891&kv1=1&kv2=12&kv3=0
num=123-456-7892&kv1=4&kv2=12&kv3=0

在文件中逐行阅读:

def get_key(data, key):
    keys = {k: v for k, v in [i.split('=') for i in data.split('&')]}
    for k, v in keys.items():
        if k == key: return int(v)
    return None

results = []

for line in [line.strip() for line in open('filename', 'r')]:
    value = get_key(line, 'kv1')
    if value:
        results.append({'kv1': value})

print results # could be [{'kv1': 2}, {'kv1': 1}, {'kv1': 4}] 

或只有一个string

with open('filename', 'r') as f: data = f.read()

keys = {k: v for k, v in [i.split('=') for i in data.split('&')]}

result = {}
for key, value in keys.items():
    if key == 'kv1':
        result[key] = int(value)

控制台i / o:

c:\nathan\python\bnutils>python
Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def get_key(data, key):
...     keys = {k: v for k, v in [i.split('=') for i in data.split('&')]}
...     for k, v in keys.items():
...         if k == key: return int(v)
...     return None
...
>>> results = []
>>> for line in [line.strip() for line in open('test.txt', 'r')]:
...     value = get_key(line, 'kv1')
...     if value:
...         results.append({'kv1': value})
...
>>> print results
[{'kv1': 2}, {'kv1': 1}, {'kv1': 4}]
>>>

的test.txt:

num=123-456-7890&kv1=2&kv2=12&kv3=0
num=123-456-7891&kv1=1&kv2=12&kv3=0
num=123-456-7892&kv1=4&kv2=12&kv3=0

答案 1 :(得分:0)

import urlparse
urlparse.parse_qs(input)

结果为:{'num':['123-456-7890'],'kv2':['12'],'kv':['1'],'kv3':['0'] }

为您汇总密钥。

答案 2 :(得分:0)

你可以这样做,所以基本上只需添加一个额外的if else块来处理关键的空案例

input='num=123-456-7890&kv=1&kv2=12&kv3=0'
result={}
for pair in input.split('&'):
    temp = pair.split('=')
    key = temp[0]
    value = [1]
    if key in 'kv1':
        if key in p:
             print value //do you really want to output this?
             result[key] += int(value)
        else:
             print value //do you really want to output this?
             result[key] = int(value)
print result['kv1']