条件达到时重置列表

时间:2015-12-11 00:05:59

标签: python list dictionary

我试图创建一个读取协议缓冲区的函数,并创建一个列表,其中列表与每个键匹配,如下所示:

Source:
  {
    name: "foo"
    ...
    some_value: "a"
    some_value: "b"
  },
  {
    name: "bar"
    ...
    some_value: "c"
    some_value: "d"
  }

Desired Output:
  {'foo': ['a','b'], 'bar': ['c','d',]}

这是我的代码:

import re

STATIC_SRC = '/path/to/my/file.txt'

def CountBrackets(line):
  if '{' in line:
    return 1
  if '}' in line:
    return -1
  else:
    return 0

with open(STATIC_SRC, 'r') as src_file:
  bracket_count = 0
  key = ''
  values = []
  my_dict = {}

  for line in src_file:
    line = line.strip()
    bracket_count += CountBrackets(line)

    # Finds line like 'name: "foo"' and stores 'foo' as key
    if line.startswith('name:'):
      key = re.findall('"([^"]*)"', line)
      key = ''.join(key)

    # Finds line like 'some_value: "a"' and adds 'a' to list
    if line.startswith('some_value:'):
      value = re.findall('"([^"]*)"', line)
      values.append(value)

    # When bracket count returns to 0, it's reached the end of a tupe
    # and should store the current key and list.
    if bracket_count == 0:
      my_dict[key] = values
      del values[:] # This is where I'm having issues.

  print(role_dict)

我的问题是我无法在元组结尾处(在源文件中)成功清除列表。我尝试了以下两种方法,都没有给出正确的输出。

Method:
  values = []
Result:
  {'foo': ['a', 'b'], 'bar': ['a','b','c','d']}

Method:
  del values[:]
Result:
  {'foo': [], 'bar': []}

我已经打印了所有键/值,因为它循环并且这些键/值正在按需运行。它还根据括号计数在写入时写入字典。似乎我用于清算的方法以某种方式清除了“价值观”。即使他们已被添加到字典中。

任何人都可以了解这里出了什么问题以及如何正确清空价值清单?谢谢!

编辑:根据要求,tl; dr

我希望程序循环使用这个逻辑:

if x:
  - store something to 'key'
if y:
  - add something to a list 'values'
if z:
  - write the current 'key' and 'values' to a dictionary
  - clear the list 'values'

如何清除最后的值列表?

1 个答案:

答案 0 :(得分:2)

我不知道你为什么要在第一次尝试时获得该输出。它对我有用。见下文。

with open(STATIC_SRC, 'r') as src_file:
  bracket_count = 0
  key = ''
  values = []
  my_dict = {}

  for line in src_file:
    print(values)
    line = line.strip()
    bracket_count += CountBrackets(line)

    # Finds line like 'name: "foo"' and stores 'foo' as key
    if line.startswith('name:'):
      key = re.findall('"([^"]*)"', line)
      key = ''.join(key)

    # Finds line like 'some_value: "a"' and adds 'a' to list
    if line.startswith('some_value:'):
      value = re.findall('"([^"]*)"', line)
      values.extend(value)  # append create a new list inside the existing list

    # When bracket count returns to 0, it's reached the end of a tupe
    # and should store the current key and list.
    if bracket_count == 0:
      my_dict[key] = values
      values = []

  print(my_dict)  # the name of the dict was wrong

结果是

{'foo': ['a', 'b'], 'bar': ['c', 'd']}

我刚刚编辑了最后一个打印件,并用extend扩展了append。

你不能del values因为它会删除dict中的值,因为它与内存中的对象相同。

d = {}
k = [1,2,3]
d['a'] = k
d
#  {'a': [1, 2, 3]}
id(d['a']) == id(k)
#  True

运行Python 2.7.6。