将字典值转换为具有特定顺序的字符串对象

时间:2019-12-17 17:13:55

标签: python python-3.x dictionary

我正在寻找创建一个函数,该函数会将具有地址值的字典转换为具有特定顺序的字符串值。我还需要考虑缺失值(某些地址不会有第二或第三条地址行。我希望输出如下所示,以便可以将用新行分隔的文本块复制到数据库字段中。 / p>

name
contact
addr1
addr2 (if not empty)
addr3 (if not empty)
city, state zip
phone

我有以下创建字典的内容,但是我坚持创建一个字符串对象,该对象将忽略空值,并按正确的顺序放置所有内容。

def setShippingAddr(name, contact, addr1, addr2, addr3, city, state, zipCode, phone):
    addDict = {'name': name, 'contact': contact, 'addr1': addr1,
               'city': city, 'state': state, 'zip': zipCode, 'phone': phone}
    if addr2 is True:    # append dict if addr2/addr 3 are True
        addDict['addr2'] = addr2
    if addr3 is True:
        addDict['addr3'] = addr3

    shAddr =     # This is where i need to create the string object
    return shAddr

5 个答案:

答案 0 :(得分:2)

看起来(假设您使用的是python3),这里可以使用f字符串。

shAddr = f"{addDict['name']} {addDict['contract'] etc..."

您可以在{}中添加逻辑,例如

{addDict['addr2'] if addDict['addr2'] else ""}

应该工作,具体取决于您要查找的特定输出是什么。

答案 1 :(得分:2)

考虑到您可能想向字典中添加新条目

def setShippingAddr(name, contact, addr1, addr2, addr3, city, state, zipCode, phone):
    addDict = {'name': name, 'contact': contact, 'addr1': addr1,
               'city': city, 'state': state, 'zip': zipCode, 'phone': phone}
    if addr2 is True:    # append dict if addr2/addr 3 are True
        addDict['addr2'] = addr2
    if addr3 is True:
        addDict['addr3'] = addr3

    shAddr = ''
    for key in addDict:
      shAddr += addDict[key] + '\n'
    return shAddr

答案 2 :(得分:2)

我将重写该函数以仅返回字符串,而不必使用字典:

def setShippingAddr(name, contact, addr1, city, state, zipCode, phone, addr2=None, addr3=None):
    shAddr = f'{name}\n{contact}\n{addr1}'
    shAddr = f'{shAddr}\n{addr2}' if addr2 else shAddr
    shAddr = f'{shAddr}\n{addr3}' if addr3 else shAddr
    shAddr = f'{shAddr}\n{city}, {state} {zipCode}\n{phone}'
    return shAddr

答案 3 :(得分:0)

我不确定我是否理解字典中的内容。您可以将其省略,对吗? 然后

def setShippingAddr(*args):
    return "\n".join([str(arg) for arg in args if arg])


s = setShippingAddr("Delenges", "Me", "Streetstreet", "Borrough", False, 
                    "Town of City", "Landcountry", 12353, "+1 555 4545454")
print(s)

打印

    Delenges
    Me
    Streetstreet
    Borrough
    Town of City
    Landcountry
    12353
    +1 555 4545454

答案 4 :(得分:0)

这是一个更加Python化的解决方案,

[array]$myFiles=Get-ChildItem *.json -Recurse| select -expand fullname

foreach ($filePath in $myFiles)
{
    $isValid = Get-Content $filePath -Raw | Test-Json -ErrorAction SilentlyContinue

    if ($isValid) 
    {
        Write-Host "Is working for $filePath"
    }
    else 
    {
        Write-Host "Not working for $filePath"
    }
}

在这种情况下,我使用了addr2,它的值为空。如果需要,可以完全省略addr2,然后在迭代时检查该值。

def dict_to_string(dic):
    s = ''
    for k, v in dic.items():
        s += "{} : {}\n".format(k, v)
    return s


addDict = {'name': 'name', 'contact': 'contact', 'addr1': 'addr1', 'addr2': '',
           'city': 'city', 'state': 'state', 'zip': 'zipCode', 'phone': 'phone'}
print(dict_to_string(addDict))

最后,如果迭代的自然顺序不是您想要的,则可以使用def dict_to_string(dic): s = '' for k, v in dic.items(): if k: s += "{} : {}\n".format(k, v) return s addDict = {'name': 'name', 'contact': 'contact', 'addr1': 'addr1', 'addr2': '', 'city': 'city', 'state': 'state', 'zip': 'zipCode', 'phone': 'phone'} print(dict_to_string(addDict))