将元组列表转换成字典

时间:2020-05-12 19:36:06

标签: python dictionary

我正在尝试将元组“ L”的列表转换成字典。我正在尝试编写一些代码,以在循环相同的键(在element [1]中)时将element [5]添加到我的值中,而不是替换该值。

L = [('super mario land 2: 6 golden coins','GB',1992,'adventure','nintendo',11180000.0),
 ('sonic the hedgehog 2', 'GEN', 1992, 'platform', 'sega', 6020000.0),
 ("kirby's dream land", 'GB', 1992, 'platform', 'nintendo', 5130000.0),
 ("the legend of zelda: link's awakening",'GB',1992,'action','nintendo',3840000.0),
 ('mortal kombat', 'GEN', 1992, 'fighting', 'arena entertainment', 2670000.0)]


D = {}

for element in L:

    D[element[1]] = element[5]




Dictionary I want:
    D = { 'GB': 20150000.0,
          'GEN': 8690000 }

4 个答案:

答案 0 :(得分:1)

您可以为此使用defaultdict

from collections import defaultdict

L = [('super mario land 2: 6 golden coins','GB',1992,'adventure','nintendo',11180000.0),
 ('sonic the hedgehog 2', 'GEN', 1992, 'platform', 'sega', 6020000.0),
 ("kirby's dream land", 'GB', 1992, 'platform', 'nintendo', 5130000.0),
 ("the legend of zelda: link's awakening",'GB',1992,'action','nintendo',3840000.0),
 ('mortal kombat', 'GEN', 1992, 'fighting', 'arena entertainment', 2670000.0)]

D = defaultdict(float)

for element in L:
    D[element[1]] += element[5]
print(D)

根据要求输出

答案 1 :(得分:0)

D = {}
for element in L:
    if element[1] in D:
        D[element[1]] += element[5]
    else:
        D[element[1]] = element[5]

答案 2 :(得分:0)

也许:

for element in L:
    if not element[1] in D.keys():
         D[element[1]] = element[5]
     else:
         D[element[1]] += element[5]

答案 3 :(得分:0)

仅是一种乐趣,一种解决方案

# TryToMock.py

from pathlib import Path
import yaml

# In my current working folder, I have to .yaml files containing the following
# content for illustrative purpose:
#
# file1.yaml = {'name': 'test1', 'file_type': 'yaml'}
# file2.yaml = {'schema': 'test2', 'currencies': ['EUR', 'USD', 'JPY']}


class TryToMock:
    def __init__(self, file_to_mock_1, file_to_mock_2):
        self._file_to_mock_1 = file_to_mock_1
        self._file_to_mock_2 = file_to_mock_2

    def load_files(self):
        with Path.open(self._file_to_mock_1) as f:
            file1 = yaml.load(f, Loader=yaml.FullLoader)

        with Path.open(self._file_to_mock_2) as f:
            file2 = yaml.load(f, Loader=yaml.FullLoader)

        return file1, file2




# test_TryToMock.py

import os
from pathlib import Path

import pytest
import yaml

from tests import TryToMock


def yaml_files_for_test(yaml_content):
    names = {"file1.yaml": file1_content, "file2.yaml": file2_content}
    return os.path.join("./", names[os.path.basename(yaml_content)])


@pytest.fixture(scope="module")
def file1_content():
    with Path.open(Path("./file1.yaml")) as f:
        return yaml.load(f, Loader=yaml.FullLoader)


@pytest.fixture(scope="module")
def file2_content():
    with Path.open(Path("./file2.yaml")) as f:
        return yaml.load(f, Loader=yaml.FullLoader)


def test_try_to_mock(file1_content, file2_content, monkeypatch, mocker):
    file_1 = Path("./file1.yaml")
    file_2 = Path("./file2.yaml")

    m = TryToMock.TryToMock(file_to_mock_1=file_1, file_to_mock_2=file_2)

    # Change some items
    monkeypatch.setitem(file1_content, "file_type", "json")

    # Mocking - How does it work when I would like to use mock_open???
    # How should the lambda function look like?
    mocker.patch(
        "pathlib.Path.open",
        lambda x: mocker.mock_open(read_data=yaml_files_for_test(x)),
    )

    files = m.load_files()
    assert files[0]["file_type"] == "json"

你得到

L = [('super mario land 2: 6 golden coins','GB',1992,'adventure','nintendo',11180000.0), ('sonic the hedgehog 2', 'GEN', 1992, 'platform', 'sega', 6020000.0), ("kirby's dream land", 'GB', 1992, 'platform', 'nintendo', 5130000.0), ("the legend of zelda: link's awakening",'GB',1992,'action','nintendo',3840000.0), ('mortal kombat', 'GEN', 1992, 'fighting', 'arena entertainment', 2670000.0)]

from itertools import groupby
from operator import itemgetter
from functools import reduce
dict([(K,reduce(lambda x,y:x+y,[e[-1] for e in T])) for K,T in groupby(sorted(L,key=itemgetter(1)),itemgetter(1))])