简体   繁体   English

如何将两个列表的值存储在单个字典中,其中第一个列表的值是键,第二个列表的值是属性?

[英]How to store the values of two lists in a single dictionary where values of first list is a key and the values of second list are attributes?

road= []
distance=[]
i= input ('THE NUMBER OF NODES TO TEST')
for i in range(0,i):
    a = input(' THE NODE NUMBER \n')
    b= input ('ENTER NODE VALUE \n')

    road.append(a)
    distance.append(b)  
    print 'THE NODES AND RESPECTIVE VALUES ARE'
    print "NODES:  \t | \t VALUES:\n " ,words, distance

In above python sample code road and distance are two lists which will store the value input by the user. 在上面的python示例代码中,road和distance是两个列表,它们将存储用户输入的值。 Now I want to add those data in a dictionary where road[0]:distance[0], road[1]: distance[1] and so on. 现在,我想将这些数据添加到字典中,其中的字典是road[0]:distance[0], road[1]: distance[1]等。 ie The values inserted in the list 'road' and 'distance' should be included in a new dictionary say 'map'which is somehow like this map={"road":"distance"} 即插入列表“ road”和“ distance”中的值应包含在新字典中,例如“ map”,这有点像此map = {“ road”:“ distance”}

Use zip and dict built-in functions. 使用zipdict内置函数。

dict(zip(road,distance))

Example: 例:

>>> road = ['foo', 'bar']
>>> distance = [1,2]
>>> dict(zip(road,distance))
{'foo': 1, 'bar': 2}

using zip will save your time. 使用zip可以节省您的时间。

But simple code is: 但是简单的代码是:

road = [1,2,3,4,5]
distance = [100,150,120,150,200]
dict = {}
for i in range(0, len(road)):
    dict[road[i]] = distance[i]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在单个 dict 中转换 dict 列表(带有 2 个键/值),其中第一个键的值是第二个值的键 - Transform list of dict (with 2 keys/values) in a single dict where values of first key is the key of the second value 如何根据条件将第二个字典列表的键及其值添加到字典的第一个列表中 - How shall I add one of the key and its values of second list of dictionary to the first list of dictionary based on the condition 如何创建具有 2 个键的字典,其中第一个键是索引,第二个键来自列表,值来自 df 的列? - How can I create a dictionary with 2 keys where the the first key is the index, the second key is from a list and the values from columns of a df? 带有单键和两个值的Python存储列表 - Python store lists with single key and two values 将两个值添加到列表中的一个键,并将列表添加到字典中 - Adding two values to one key in lists and add the list to dictionary 如何将值列表添加到字典中,其中列表中的第一个元素属于第一个键等等......? - How can I add a list of values to a dictionary where the first element in the list belongs to the first key and so on...? 在两个列表中,如何根据第一个列表值获取第二个列表的值? - In two lists, How do I get the values of the second list based on the first list value? 将列表列表转换为具有多个键值的字典 - Converting list of lists to a dictionary with multiple values for a key 如何将列表列表组合成字典,其中第一个子列表映射到所有后续子列表中的相应值? - How to combine a list of lists into a dictionary where the first sublist is mapped to corresponding values in all subsequent sublists? 将两个列表转换为带有值作为列表的字典 - Convert two lists to dictionary with values as list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM