简体   繁体   中英

Adding tuple to as keys dictionary

I'm trying to add a tuple as values, while iterating through the list of keys in a dictionary. I'm sure there's a way to do it with list comprehension, but I couldn't get it to work in the keys. For simplicity's sake, here is the concept:

myDict = {"Last name", "First name"}
myTuple = ("Miller", "Joe")
for key in myDict:
    myDict.update(zip({key:n for n in myTuple}))

First, your myDict is a set , not a dict . Using curly braces ( {} ) without any values will result in a set . The problem with set s is they are not ordered. You can simply do this if you change both to tuples (or list s, for this purpose):

myKeys = ("Last name", "First name")
myValues = ("Miller", "Joe")
print(dict(zip(myKeys, myValues)))

which will print the following dict:

{'Last name': 'Miller', 'First name': 'Joe'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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