所以我需要一种用于在python中创建字典列表的最佳方法。
所以我有一个看起来像这样的列表:
'key'=>env(APP_KEY,'base64key')
所以我需要这样的输出:
[
{'name': 'John', 'hobbies': ['Reading', 'Swimming']},
{'name': 'Gina', 'hobbies': ['Skating', 'Cooking']},
{'name': 'John', 'hobbies': ['Gardening', 'Swimming']}
]
如您所见,我需要为每个名称创建一组爱好,并且确实创建一个唯一的字典列表。
这是我尝试过的:
[
{'name': 'John', 'hobbies': ['Reading', 'Swimming', 'Gardening']},
{'name': 'Gina', 'hobbies': ['Skating', 'Cooking']},
]
但是并不需要创建一个集
有人可以以最佳方式帮助我吗?
谢谢。
答案 0 :(得分:1)
如果您同意将输出的结构从名称更改为爱好集,而只是将其更改为词典,则可以在线性时间内完成(忽略边缘情况,即很多哈希冲突):
from collections import defaultdict
data = [
{'name': 'John', 'hobbies': ['Reading', 'Swimming']},
{'name': 'Gina', 'hobbies': ['Skating', 'Cooking']},
{'name': 'John', 'hobbies': ['Gardening', 'Swimming']}
]
output = defaultdict(set)
for d in data:
output[d['name']].update(d['hobbies'])
print(output)
# defaultdict(<class 'set'>, {'John': {'Reading', 'Swimming', 'Gardening'},
# 'Gina': {'Cooking', 'Skating'}})
如果您坚持使用字典列表,您仍然可以实现几乎线性时间(列表查找仍为O(n)),但具有将索引映射到名称的逻辑:
data = [
{'name': 'John', 'hobbies': ['Reading', 'Swimming']},
{'name': 'Gina', 'hobbies': ['Skating', 'Cooking']},
{'name': 'John', 'hobbies': ['Gardening', 'Swimming']}
]
output = []
names_to_indices = {}
for d in data:
if d['name'] not in names_to_indices:
output.append({'name': d['name'], 'hobbies': d['hobbies']})
names_to_indices[d['name']] = len(output) - 1
else:
index = names_to_indices[d['name']]
for hobbie in d['hobbies']:
if hobbie not in output[index]['hobbies']:
output[index]['hobbies'].append(hobbie)
print(output)
# [{'name': 'John', 'hobbies': ['Reading', 'Swimming', 'Gardening']},
# {'name': 'Gina', 'hobbies': ['Skating', 'Cooking']}]
如果您同意将业余爱好定为一组,则可以将其设为真正的线性时间(同样,如果我们忽略过多的哈希冲突的可能性),
data = [
{'name': 'John', 'hobbies': ['Reading', 'Swimming']},
{'name': 'Gina', 'hobbies': ['Skating', 'Cooking']},
{'name': 'John', 'hobbies': ['Gardening', 'Swimming']}
]
output = []
names_to_indices = {}
for d in data:
if d['name'] not in names_to_indices:
output.append({'name': d['name'], 'hobbies': set(d['hobbies'])})
names_to_indices[d['name']] = len(output) - 1
else:
index = names_to_indices[d['name']]
output[index]['hobbies'].update(d['hobbies'])
print(output)
# [{'name': 'John', 'hobbies': {'Gardening', 'Swimming', 'Reading'}},
# {'name': 'Gina', 'hobbies': {'Skating', 'Cooking'}}]
答案 1 :(得分:1)
只需构造一个中间默认字典,即可使您在线性时间内完成此操作。最后转换回所需的结构。
inp = [
{'name': 'John', 'hobbies': ['Reading', 'Swimming']},
{'name': 'Gina', 'hobbies': ['Skating', 'Cooking']},
{'name': 'John', 'hobbies': ['Gardening', 'Swimming']}
]
from collections import defaultdict
temp = defaultdict(set)
for d in inp:
temp[d['name']].update(d['hobbies'])
result = [{'name':k, 'hobbies': list(v)} for k, v in temp.items()]
输出:
[{'name': 'John', 'hobbies': ['Gardening', 'Reading', 'Swimming']},
{'name': 'Gina', 'hobbies': ['Cooking', 'Skating']}]