如何将列表转换为dict?

时间:2018-01-18 01:11:49

标签: python python-3.x dictionary

我有这样的名单:

newpackage

如何使用名为['7801234567', 'Robert Post', '66 Hinton Road'] ['7809876543', 'Farrukh Ahmed', '101 Edson Crest'] ['7803214567', 'Md Toukir Imam', '34 Sherwood Park Avenue'] ['7807890123', 'Elham Ahmadi', '8 Devon Place'] ['7808907654', 'Rong Feng', '32 Spruce Street'] ['7801236789', 'Nazanin Tahmasebi', '98 Albert Avenue'] ['7804321098', 'Sayem Mohammad Siam', '56 Stony Place'] ['7808765432', 'Amir Hossein Faghih Dinevari', '45 Beautiful Street'] 'tel''name'的键将它们转换为词典?

3 个答案:

答案 0 :(得分:2)

使用zip将键与其值按索引关联

keys = ('tel', 'name', 'address')
values = ['7801234567', 'Robert Post', '66 Hinton Road']

d = dict(zip(keys, values))
# {'tel': '7801234567', 'name': 'Robert Post', 'address': '66 Hinton Road'}

编辑:

显然,您可以使用此技术创建更复杂的结构。

info = [['7801234567', 'Robert Post', '66 Hinton Road'],
        ['7809876543', 'Farrukh Ahmed', '101 Edson Crest'],
        ['7803214567', 'Md Toukir Imam', '34 Sherwood Park Avenue'],
        ['7807890123', 'Elham Ahmadi', '8 Devon Place'],
        ['7808907654', 'Rong Feng', '32 Spruce Street'],
        ['7801236789', 'Nazanin Tahmasebi', '98 Albert Avenue'],
        ['7804321098', 'Sayem Mohammad Siam', '56 Stony Place'], 
        ['7808765432', 'Amir Hossein Faghih Dinevari', '45 Beautiful Street']]
keys = ('tel', 'name', 'address')

dictionaries = [dict(zip(keys, values)) for values in info]

[_ for _ in _]被称为list comprehension

答案 1 :(得分:1)

我们假设数据为:

app.Use(async (context, _next) => {

    if (string.IsNullOrEmpty(context.Request.Path.ToString())
            || context.Request.Path.ToString() == "/")
    {
        context.Response.StatusCode = 200;
        await context.Response.WriteAsync("Web API is now running.");
    }
    else
        await _next();
});

info_row = [['7801234567', 'Robert Post', '66 Hinton Road'],
 ['7809876543', 'Farrukh Ahmed', '101 Edson Crest'],
 ['7803214567', 'Md Toukir Imam', '34 Sherwood Park Avenue'],
 ...,
]

我们可以先编写一个函数来转换每个“行”列表。

info_type = ['tel', 'name', 'address']

然后,我们可以使用列表推导将这样的函数应用于整个列表列表。

def convert_row(row_name, row_content):
    d = dict()
    for i, j in enumerate(row_name):
        d[j] = row_content[i]
    return d

正如另一个答案所指出的,我们可以使用expected_result = [convert_row(info_type, r) for r in info_row] 。在大多数情况下,使用内置例程是非常鼓励的。所以最好输入

zip

答案 2 :(得分:0)

您可以在列表理解中执行此操作:

/*
 * GameState.hpp
 */
#ifndef GameState_HPP
#define GameState_HPP

#include "stdafx.h"
#include "GameLoopObject.hpp"

/// gamestate base class
class GameState : public GameLoopObject {
public:
    GameState(sf::RenderWindow & w); //: GameLoopObject(w) {}; // constructor
    virtual ~GameState(); // destructor

    /*
     * Game Loop functions
     */
    virtual void Update();
    virtual void Draw();
    virtual void HandleInput();
    virtual void Reset();
};

#endif //GameState_HPP


/*
 * GameStateManager.hpp
 */
#ifndef GameStateManager_HPP
#define GameStateManager_HPP

#include "stdafx.h"
#include "GameLoopObject.hpp"
#include "GameState.hpp"
#include<string>
#include<map>

class GameStateManager : public GameLoopObject {
private:
    GameState * currentState;
    GameState * nextState;
public:
    std::map<std::string, GameState> gameStates{}; // list where all known gamestates are stored.
    // methods
    GameStateManager(sf::RenderWindow & w);
    void AddGameState(std::string name, GameState * state);
    void SetNext(std::string name);
    void SwitchState();
    void HandleInput(); 
    void Update();
    void Draw();
    void Reset();
};

#endif //GameStateManager_HPP

哪个输出:

data = [['7801234567', 'Robert Post', '66 Hinton Road'],
        ['7809876543', 'Farrukh Ahmed', '101 Edson Crest'],
        ['7803214567', 'Md Toukir Imam', '34 Sherwood Park Avenue'],
        ['7807890123', 'Elham Ahmadi', '8 Devon Place'],
        ['7808907654', 'Rong Feng', '32 Spruce Street'],
        ['7801236789', 'Nazanin Tahmasebi', '98 Albert Avenue'],
        ['7804321098', 'Sayem Mohammad Siam', '56 Stony Place'],
        ['7808765432', 'Amir Hossein Faghih Dinevari', '45 Beautiful Street']]

new_data = [{'tel': tel, 'name': name, 'address': address} for tel, name, address in data]

print(new_data)