python - 以最快和可扩展的方式从另一个字典创建字典

标签 python python-2.7 python-3.x

我几乎没有创建新字典的场景:

  1. 只取列表中键'total'不为零的那些字典
  2. 从字典中删除关键字,例如“total”和“rank”
  3. 使用'name'键值作为key,'game'键值作为列表
    新字典中的值
  4. 对新字典中的值列表进行排序

我的代码是:

# input dictionary
data =[
           {'name': 'foo', 'rank': 3, 'game': 'football', 'total': 1},
           {'name': 'bar', 'rank': 5, 'game': 'hockey', 'total': 0},
           {'name': 'foo', 'rank': 7, 'game': 'tennis', 'total': 0},
           {'name': 'foo', 'rank': 2, 'game': 'cricket', 'total': 2},
           {'name': 'bar', 'rank': 1, 'game': 'cricket', 'total': 8},
        ]

result_list = []
merged_data = {}
result_data = {}

# Get the list of dict if key 'total' value is not zero
dict_without_total = [
    den for den in data if den.get('total')
]

for my_dict in dict_without_total:

    # deleting key 'brand' and 'total' from the
    del my_dict['rank']
    del my_dict['total']

    result_data.update({
        my_dict.get('name'): (my_dict.get('game'))
    })
    result_list.append(result_data)

# store all values of same keys in list and sort the values list
for result in result_list:
    for keys, values in result.items():
        if keys not in merged_data:
            merged_data[keys] = []

        merged_data[keys].append(values)
        merged_data[keys].sort()

print merged_data

我的代码输出:

{
    'bar': ['cricket', 'cricket', 'cricket'],
    'foo': ['cricket', 'cricket', 'cricket']
}

预期结果:

{
   'foo': ['cricket', 'football'],
   'bar': ['cricket']
}

是否有更快的方法来获取结果,或者我可以使用一些 python 内置函数来处理这种情况?

最佳答案

你真的可以简化这个,因为不需要修改现有的字典。保留原始数据结构并构建一个新数据结构通常会干净得多。

data = [
    {'name': 'foo', 'rank': 3, 'game': 'football', 'total': 1},
    {'name': 'bar', 'rank': 5, 'game': 'hockey', 'total': 0},
    {'name': 'foo', 'rank': 7, 'game': 'tennis', 'total': 0},
    {'name': 'foo', 'rank': 2, 'game': 'cricket', 'total': 2},
    {'name': 'bar', 'rank': 1, 'game': 'cricket', 'total': 8},
]

result = {}

for e in data:
    if e["total"]:
        name = e["name"]
        if name not in result:
            result[name] = []
        result[name].append(e["game"])

print result

结果是 {'foo': ['football', 'cricket'], 'bar': ['cricket']} 这就是您要查找的内容。

关于python - 以最快和可扩展的方式从另一个字典创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38891514/

相关文章:

python嵌入: passing list from C to python function

python-3.x - python 3 pyinstaller 始终给出 "failed to create process"

python - 在 python3 中检测到输入之前如何执行某些操作?

python - 快速加载和处理9000万个元素的字典

python - 向空的二维 NumPy 数组添加行

python - 使用套接字编程在python中创建消息系统

python-3.x - Sqlalchemy 从关系中获取数据

Python 2.7 - 将一系列拆分为具有相同数量项目的间隔(与 pandas.cut() 类似)

python - 没有类的 Pygame 碰撞

python - `print` 解释为空白是什么?