Python将csv文件中的名称读入字典,并为每个名称

时间:2017-11-08 22:39:01

标签: python csv dictionary

我在使用播放器名称的csv文件在Python中创建字典时遇到问题。以下是我的代码示例:

playerNames = []
with open(player_names) as csvfile
    for row in csv.reader(csvfile)
        playerNames.append(row)

这段代码基本上会从csv文件中读取名称并将它们放入一个如下所示的嵌套列表中:[[P1],[P2],[P3],[P4]]

现在我想将这些播放器名称添加到字典中,并为字典中的每个播放器添加值0,所需的结果将如下所示:{P1:0,P2:0,P3 :0,P4:0}但是,我正在努力做到这一点,并非常感谢一些帮助。我还想问一下,是否有可能直接将这些播放器名称读入字典,而不是先将它们读入列表?

对于使用这个或一些示例代码的任何帮助都会非常感激,因为我不熟悉使用词典

谢谢,

3 个答案:

答案 0 :(得分:0)

<?php $host = $_SERVER['HTTP_HOST']; if (isset($_POST['action'])) { $email = $_POST['email']; //obtain email from post, place into $email variable $email = filter_var($email, FILTER_SANITIZE_EMAIL); //sanitizing email //$theAction = $_POST['action']; //wpSubscription($host, $email, $theAction); //$redirect = $_POST['redirect']; //header('Location: ' . $redirect); if ($_POST['email'] == '') { echo "Please enter an email address"; } if ($host == network_site_url()) { $sh_param = array( //setting username & password array 'UserName' => "", 'Password' => "" ); $authvalues = new SoapVar($sh_param, SOAP_ENC_OBJECT); //encoding username and password array $headers[] = new SoapHeader("http://webservices.listrak.com/v31/", 'WSUser', $sh_param); $soapClient = new SoapClient("https://webservices.listrak.com/v31/IntegrationService.asmx?WSDL", array( 'trace' => 1, 'exceptions' => true, 'cache_wsdl' => WSDL_CACHE_NONE, 'soap_version' => SOAP_1_2 )); $soapClient->__setSoapHeaders($headers); $params = array( //parameters for soap xml integration with listrak 'WSContact' => array( 'EmailAddress' => $email, 'ListID' => '' ), 'ProfileUpdateType' => 'Overwrite', 'ExternalEventIDs' => '', 'OverrideUnsubscribe' => true ); try { $rest = $soapClient->SetContact($params); //using SetContact method, send parameters } catch (SoapFault $e) { //if an error occurs, display it echo '<pre>'; print($e->getMessage()); echo '</pre>'; } } } ?> 替换为playerNames = [],将playerNames = {}替换为playerNames.append(row)。并且&#34;添加&#34; 0并不是一个非常正确的术语:你为每个键分配零。

答案 1 :(得分:0)

假设每个玩家的名字在输入文件中只出现一次:

[remote "foo"]
        token = 1894701a
        skipFetchAll = true

输出:

player_dict = {}
with open('player_names.txt') as players:
    for line in players:
        player_dict[line.strip()]=0

print(player_dict)

答案 2 :(得分:0)

使用嵌套的名称列表,您可以使用以下内容:

playerDict = dict.fromkeys([p[0] for p in playerNames, 0])

甚至:

playerDict = {p[0]:0 for p in playerNames}

但我建议您只通过附加名称进行以下更改来仅列出名称列表(而不是嵌套列表):

playerNames.append(row[0])