字典列表没有按预期工作

问题描述 投票:1回答:3

由于某些原因,我的小小脑子有这个问题,我有一个元组list = [('name:john','age:25','location:brazil'),('name:terry','age:32','location:acme')]列表。我试图将这些值移动到字典中以便稍后解析。我做了一些尝试,低于最新的这些并且我没有将所有结果都放入dict中,dict最终得到迭代的最后一个值(每次重新创建dict)。

people = {}

list = [('name:john','age:25','location:brazil'),('name:terry','age:32','location:acme')]

for value in list:
        people = {'person': [dict(item.split(":",1) for item in value)]}
python dictionary
3个回答
1
投票

你也可以尝试这个:

inlist = [('name:john','age:25','location:brazil'),('name:terry','age:32','location:acme')]
d = []

for tup in inlist:
    tempDict = {}
    for elem in tup:
        elem = elem.split(":")
        tempDict.update({elem[0]:elem[1]})
    d.append({'person':tempDict})

print(d)

输出:

[{'person': {'location': 'brazil', 'name': 'john', 'age': '25'}}, {'person': {'location': 'acme', 'name': 'terry', 'age': '32'}}]

如果你想要一个带有密钥person的字典,并用字符的信息来定义字典,那么用d.append({'person':tempDict})替换d.append(tempDict)并在打印前添加d = {'person':d}

输出:

{'person': [{'location': 'brazil', 'name': 'john', 'age': '25'}, {'location': 'acme', 'name': 'terry', 'age': '32'}]}

0
投票

你可以试试这个:

l = [('name:john','age:25','location:brazil'),('person:terry','age:32','location:acme')]
people = [{c:d for c, d in [i.split(':') for i in a]} for a in l]

输出:

[{'name': 'john', 'age': '25', 'location': 'brazil'}, {'person': 'terry', 'age': '32', 'location': 'acme'}]

0
投票

首先尽量不要打电话给你的清单。这个名称在python中受到保护,通常用于从迭代器或范围等中获取列表。我首先列出人员列表,然后将每个人作为单独的字典附加到人员列表中,如下所示:

people = []

my_list = [('name:john','age:25','location:brazil'),('person:terry','age:32','location:acme')]

for tup in my_list:
    person = {}
    for item in tup:
        splitted = item.split(':')
        person.update({splitted[0]:splitted[1]})
    people.append(person)

输出然后是这样的:

[{'age': '25', 'location': 'brazil', 'name': 'john'},
 {'age': '32', 'location': 'acme', 'person': 'terry'}]
© www.soinside.com 2019 - 2024. All rights reserved.