If I have a dictionary such as:
clues = {'w':'e','r':'t'}
How do I get the first of each letter in the two to join together in a string, it is something like...
for clue in clues:
clue = ''.join(
However I don't know how to get them into a string from this...
Edit:
You can use a list comprehension for that:
>>> clues = {'w':'e','r':'t'}
>>> [''.join(x) for x in (clues, clues.values())]
['wr', 'et']
>>>
how would you get the first of each letter in the two to join together in a string
I think you are talking about the dictionary's keys. If so, then you can use str.join
:
>>> clues = {'w':'e','r':'t'}
>>> ''.join(clues)
'wr'
>>>
Also, iterating over a dictionary (which is what str.join
is doing) will yield its keys. Thus, there is no need to do:
''.join(clues.keys())
Finally, @DSM made a good point. Dictionaries are naturally unordered in Python. Meaning, you could get rw
just as easily as you get wr
.
If you want a dictionary with guarunteed order, check out collections.OrderedDict
.
如果要将所有键都连接到字符串中,请尝试以下操作:
''.join(clues.keys())
It's not entirely clear what your question is, but if you want to join
the key
and value
together, storing that result into a new set
, this would be the solution:
>>> {''.join(key_value) for key_value in clues.items()}
set(['rt', 'we'])
Written long hand for clarity:
out_set = set()
for key_value in clues.items():
key_value_joined = ''.join(key_value)
out_set.add(key_value_joined)
这应该可以解决问题:
''.join(clues.keys())
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.