我可以使用列表理解语法来创建词典吗?

例如,通过迭代成对的键和值:

d = {... for k, v in zip(keys, values)}

当前回答

这种方法使用for循环对给定日期进行迭代。

Syntax: {key: value for (key, value) in data}

Eg:

# create a list comprehension with country and code:
    Country_code = [('China', 86), ('USA', 1),
            ('Ghana', 233), ('Uk', 44)]

# use iterable method to show results
{key: value for (key, value) in Country_code}

其他回答

试试这个,

def get_dic_from_two_lists(keys, values):
    return { keys[i] : values[i] for i in range(len(keys)) }

假设我们有两个列表国家和首都

country = ['India', 'Pakistan', 'China']
capital = ['New Delhi', 'Islamabad', 'Beijing']

然后从两个列表中创建字典:

print get_dic_from_two_lists(country, capital)

输出是这样的,

{'Pakistan': 'Islamabad', 'China': 'Beijing', 'India': 'New Delhi'}

这种方法使用for循环对给定日期进行迭代。

Syntax: {key: value for (key, value) in data}

Eg:

# create a list comprehension with country and code:
    Country_code = [('China', 86), ('USA', 1),
            ('Ghana', 233), ('Uk', 44)]

# use iterable method to show results
{key: value for (key, value) in Country_code}

要添加到@fortran的答案中,如果您想要遍历键列表key_list以及值列表value_list:

d = dict((key, value) for (key, value) in zip(key_list, value_list))

or

d = {(key, value) for (key, value) in zip(key_list, value_list)}

再举一个例子。假设您有以下列表:

nums = [4,2,2,1,3]

您希望将其转换为dict,其中键是索引,值是列表中的元素。您可以使用以下代码行执行此操作:

{index:nums[index] for index in range(0,len(nums))}

在Python 2.7中,它类似于:

>>> list1, list2 = ['a', 'b', 'c'], [1,2,3]
>>> dict( zip( list1, list2))
{'a': 1, 'c': 3, 'b': 2}

给他们拉链!