简体   繁体   English

将 2 个列表和一个字符串转换为字典

[英]Converting 2 list and one string to dictionary

P.S: Thank you everybody ,esp Matthias Fripp . Just reviewed  the question You are right I made mistake : String is value not the key 
num=[1,2,3,4,5,6]
pow=[1,4,9,16,25,36]
s= ":subtraction"    
dic={1:1 ,0:s , 2:4,2:s, 3:9,6:s, 4:16,12:s.......}

There is easy way to convert two list to dictionary :有一种简单的方法可以将两个列表转换为字典:

newdic=dict(zip(list1,list2))

but for this problem no clue even with comprehension:但是对于这个问题,即使理解也没有线索:

print({num[i]:pow[i] for i in range(len(num))})

In principle, this would do what you want:原则上,这会做你想做的:

nums = [(n, p) for (n, p) in zip(num, pow)]
diffs = [('subtraction', p-n) for (n, p) in zip(num, pow)]
items = nums + diffs
dic = dict(items)

However, a dictionary cannot have multiple items with the same key, so each of your "subtraction" items will be replaced by the next one added to the dictionary, and you'll only get the last one.但是,字典不能有多个具有相同键的项目,因此您的每个“减法”项目都将被添加到字典中的下一个项目替换,而您只会得到最后一个项目。 So you might prefer to work with the items list directly.因此,您可能更喜欢直接使用items列表。

If you need the items list sorted as you've shown, that will take a little more work.如果您需要按照您显示的方式对items列表进行排序,则需要做更多的工作。 Maybe something like this:也许是这样的:

items = []
for n, p in zip(num, pow):
    items.append((n, p))
    items.append(('subtraction', p-n))
# the next line will drop most 'subtraction' entries, but on 
# Python 3.7+, it will at least preserve the order (not possible 
# with earlier versions of Python)
dic = dict(items)

As others have said, dict cannot contain duplicate keys.正如其他人所说, dict不能包含重复的键。 You can make key duplicate with a little bit of tweaking.您可以通过一些调整来复制密钥。 I used OrderedDict to keep order of inserted keys:我使用OrderedDict来保持插入键的顺序:

from pprint import pprint
from collections import OrderedDict

num=[1,2,3,4,5,6]
pow=[1,4,9,16,25,36]

pprint(OrderedDict(sum([[[a, b], ['substraction ({}-{}):'.format(a, b), a-b]] for a, b in zip(num, pow)], [])))

Prints:印刷:

OrderedDict([(1, 1),
             ('substraction (1-1):', 0),
             (2, 4),
             ('substraction (2-4):', -2),
             (3, 9),
             ('substraction (3-9):', -6),
             (4, 16),
             ('substraction (4-16):', -12),
             (5, 25),
             ('substraction (5-25):', -20),
             (6, 36),
             ('substraction (6-36):', -30)])

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM