将字典值映射到列表

时间:2015-10-12 10:11:43

标签: python list dictionary

给出以下字典:

dct = {'a':3, 'b':3,'c':5,'d':3}

如何将这些值应用于以下列表:

lst = ['c', 'd', 'a', 'b', 'd']

为了获得类似的东西:

lstval = [5, 3, 3, 3, 3]

9 个答案:

答案 0 :(得分:38)

使用map

>>> map(dct.get, lst)
[5, 3, 3, 3, 3]

使用list comprehension

>>> [dct[k] for k in lst]
[5, 3, 3, 3, 3]

答案 1 :(得分:13)

您可以使用列表推导:

lstval = [ dct.get(k, your_fav_default) for k in lst ]

我个人建议使用内置map的列表推导,因为它看起来很熟悉所有Python程序员,如果需要自定义默认值,则更容易解析和扩展。

答案 2 :(得分:9)

您可以使用map函数迭代列表中的键:

lstval = list(map(dct.get, lst))

或者如果你更喜欢列表理解:

lstval = [dct[key] for key in lst]

答案 3 :(得分:6)

lstval = [d[x] for x in lst]

不要将字典命名为dictdict是该类型的名称。

答案 4 :(得分:3)

不要使用dict作为变量名称,因为它是内置的。

>>> d = {'a':3, 'b':3,'c':5,'d':3}
>>> lst = ['c', 'd', 'a', 'b', 'd']
>>> map(lambda x:d.get(x, None), lst)
[5, 3, 3, 3, 3]

答案 5 :(得分:2)

我会使用列表理解:

trait MyTrait {
    public function func() {
        echo "func in MyTrait\n";
    }
}

// Customer writes in his code:
class Sub1 extends Super {
    use MyTrait;
}
$sub1 = new Sub1;
$sub1->func();

interface FuncPrinterInterface { public function funcPrint(); } class FuncPrinter implements FuncPrinterInterface { public function funcPrint() { echo "func in MyTrait\n"; } } class UserClass { /** * @var FuncPrinterInterface */ protected $printer; /** * Sub1 constructor. * * @param FuncPrinterInterface $printer */ public function __construct(FuncPrinterInterface $printer) { $this->printer = $printer; } public function doSomething() { $this->printer->funcPrint(); } } $sub1 = new UserClass(new FuncPrinter()); $sub1->doSomething(); 部分用于返回默认值(在本例中为0),如果listval = [dict.get(key, 0) for key in lst] 中不存在具有此键的元素。

答案 6 :(得分:0)

在Python 3的文档中:

所以,zip(*d.items())给出结果。

d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

print(d.items())        # [('a', 1), ('c', 3), ('b', 2), ('d', 4)] in Python 2
                        # dict_items([('a', 1), ('c', 3), ('b', 2), ('d', 4)]) in Python 3

print(zip(*d.items()))  # [('a', 1), ('c', 3), ('b', 2), ('d', 4)] in Python 2
                        # <zip object at 0x7f1f8713ed40> in Python 3

k, v = zip(*d.items())
print(k)                # ('a', 'c', 'b', 'd')
print(v)                # (1, 3, 2, 4)

答案 7 :(得分:0)

将字典值映射到嵌套列表

许多人已经回答了这个问题。但是,没有人提到解决方案,以防嵌套列表。

通过将原始问题中的列表更改为列表列表

dct = {'a': 3, 'b': 3, 'c': 5, 'd': 3}    

lst = [['c', 'd'], ['a'], ['b', 'd']]

可以通过嵌套列表理解来完成映射

lstval = [[dct[e] for e in lst[idx]] for idx in range(len(lst))]

# lstval = [[5, 3], [3], [3, 3]]

答案 8 :(得分:0)

Anand S Kumar 正确地指出,当您的列表中的某个值在字典中不可用时,您会遇到问题

一个更强大的解决方案是向列表推导式添加 if/else 条件。这样你就可以确保代码不会被破坏。

这样,您只更改列表中您在字典中具有相应键的值否则保留原始值

m = {'a':3, 'b':3, 'c':5, 'd':3}
l = ['c', 'd', 'a', 'b', 'd', 'other_value']
l_updated = [m[x] if x in m else x for x in l]

[退出]

[5, 3, 3, 3, 3, 'other_value']
相关问题