python 字典中的值被转换为双引号而不是单引号

Values in python dictionary getting converted to double quotes rather than single quotes

我有一个包含以下值的字典:-

test_dict = {'a': ['a1', 'a2'], 'b': ['1.1.1.1:1111', '2.2.2.2:2222', '3.3.3.3:3333,4.4.4.4:4444', '5.5.5.5:5555']}

我需要将 3.3.3.3:33334.4.4.4:4444 之间的逗号 (,) 替换为 (',) 即(单引号逗号 space)和其他人一样。

我尝试了下面的代码,但输出带有双引号 (")

val = ','
valnew = '\', \''  # using escape characters - all are single quotes
for k, v in test_dict.items():
    for i, s in enumerate(v):
        if val in s:
           v[i] = s.replace(val, valnew)

print(test_dict)

输出:

{'a': ['a1', 'a2'], 'b': ['1.1.1.1:1111', '2.2.2.2:2222', "3.3.3.3:3333', '4.4.4.4:4444", '5.5.5.5:5555']}

预期输出:

{'a': ['a1', 'a2'], 'b': ['1.1.1.1:1111', '2.2.2.2:2222', '3.3.3.3:3333', '4.4.4.4:4444', '5.5.5.5:5555']}

求推荐。

print 正在显示字典的 representation,就好像调用了 print(repr(test_dict))

[repr returns] a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval() ..

由于该值是一个包含 ' 的字符串,因此在 字符串的 表示 期间使用 " 。示例:

print(repr("helloworld"))   # -> 'helloworld'
print(repr("hello'world"))  # -> "hello'world"

此表示通常仅用于诊断目的。如果需要编写这种特殊格式,则必须遍历字典并显式打印值 "per requirements".

如果希望获得具有明确定义的序列化规则的可靠 output/encoding,请使用 JSON、XML、YAML 等通用格式。

尝试这样的事情:

test_dict["b"] = ",".join(test_dict["b"]).split(",")

已更新:

import re

# do this once for the entire list
do_joinsplit_regex = re.compile(
    r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\:\d{1,4}"
)

for d in sample_list:
    for k,v in d.items():
        if not isinstance(v, list) or len(v) < 1:
            continue
        d[k] = ",".join(v).split(",")

您将数据与表示混淆了。单引号 space 和逗号 ', ' 列表中字符串表示的一部分 ,而不是字符串本身。

您实际上想做的是用逗号拆分字符串,例如

>>> '3,4'.split(',')
['3', '4']

您可以在列表中通过拆分和展平来执行此操作,如下所示:

[s1 for s0 in v for s1 in s0.split(',')]

所以:

>>> b = ['1', '2', '3,4', '5']  # Using simpler data for example
>>> b = [s1 for s0 in b for s1 in s0.split(',')]
>>> print(b)
['1', '2', '3', '4', '5']

'3.3.3.3:3333,4.4.4.4:4444' 是单个字符串,外引号只是 python 的显示方式。 "3.3.3.3:3333', '4.4.4.4:4444" 也是一样——它是一个字符串。外部双引号只是 python 向您显示字符串的方式。内部的单引号和逗号字面上就是字符串中的那些字符。

您的问题似乎是列表中的某些值已被合并。问题可能出在列表的开头。我们可以通过拆分字符串和扩展列表来修复它。没有嵌入逗号的列表项目拆分为单个项目列表,因此作为单个项目扩展到我们的新列表中。没变化。但是带逗号的项目拆分为 2 项列表并将新列表扩展 2.

test_dict = {'a': ['a1', 'a2'], 'b': ['1.1.1.1:1111', '2.2.2.2:2222', '3.3.3.3:3333,4.4.4.4:4444', '5.5.5.5:5555']}

def list_expander(alist):
    """Return list where values with a comma are expanded"""
    new_list = []
    for value in alist:
        new_list.extend(value.split(","))
    return new_list

new_dict = {key:list_expander(val) for key, val in test_dict.items()}
print(new_dict)

结果是

{'a': ['a1', 'a2'], 'b': ['1.1.1.1:1111', '2.2.2.2:2222', '3.3.3.3:3333', '4.4.4.4:4444', '5.5.5.5:5555']}