从字典中访问元素?蟒蛇

时间:2016-11-23 07:55:17

标签: python dictionary

我试图通过给它们变量来访问字典中的元素,以便我可以在其他函数中使用它们,但它会告诉我它没有被定义。

我正在使用的文件(mood.txt):

(
    [q] => Array
        (
            [0] => cars
        )

    [manufacturer] => Array
        (
            [0] => Audi
            [1] => Mercedes
        )

    [model] => Array
        (
            [0] => BMW - X5
            [1] => Mercedes - C
        )

)

我的代码:

foreach($newFacetArray as $val => $count) {
    if(strlen($val) != 0) {
        if(isset($activeFilters[$value])) {
            if(in_array($val,$activeFilters[$value])) {
                foreach($activeFilters[$value] as $af) {
                    if($af == $val) {
                        $as = array_search($val,$activeFilters[$value]);
                        unset($activeFilters[$value][$as]);
                    } else {
                        if($af != $val) {
                            $activeFilters[$value][] = $val;
                        }
                    }
                }
            }
        }

        $url = http_build_query($activeFilters);
        #$url = $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'].'&'.(($value == 'manufacturerName')?$value.'[]':$value).'='.$val;

        echo '<li class="list-group-item"><a class="attribute-loader" href="'.$url.'"><input type="checkbox" name="'.$value.'" '.$facetSearch->verifyIfChecked($_GET,$val).'/> ' . $val . ' <span class="pull-right">'.$count.'</span></a></li>';
    }
}

我一直收到这个错误:

happy, Jennifer Clause
happy, Jake Foster
sad, Jonathan Bower
mad, Penny
excited, Logan 
awkward, Mason Tyme

我希望有人可以向我解释我做错了什么!谢谢!

2 个答案:

答案 0 :(得分:1)

您没有在函数中定义name。使用moodDict[mood]来命名:

def printMood(mood, moodDict):
    if mood in moodDict:
        print("The people who are", mood, ":", moodDict[mood])

或者只使用接受默认参数的dict.get()属性,以便在密钥不存在时返回。这使得你可以获得if条件以及每次迭代中的比较:

def printMood(mood, moodDict):
    print("The people who are", mood, ":", moodDict.get(mood, '-')) #  you can use any default string instead of '-'.

答案 1 :(得分:0)

我猜这一行是问题所在:

.footer {
  background: #000;
  color: #fff;
}

.sub-footer {
  margin-bottom: 10px;
}

尝试:

if mood in moodDict:
    print("The people who are", mood, ":", name)