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.
And if you want all the keys joined into a string, try this:
''.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)
This should do the trick:
''.join(clues.keys())
Related
I have a list of one-item dicts (parsed from JSON) that looks like this:
lst = [
{"key_0": "value_0"},
{"key_1": "value_1"},
{"key_2": "value_2"},
...
{"key_n": "value_n"}
]
what would be the most elegant way to retrieve a key from the list's n-element not knowing this key?
I came up with:
[*lst[n].keys()][0]
but it looks somewhat ugly to me.
You can create an iterator from the dict and use the next function to obtain the first item:
next(iter(lst[n]))
You can convert direct keys to list and then get first item
>>> n = 0
>>> list(lst[n])[0]
'key_0'
I want to transform string like "a=b,c=d,e=f..etc"
But i don't know if there is a better way to transform from string to list
It looks ugly but it works.
string_a="a=b,b=c"
list_a=[[x.split('=')[0],x.split('=')[1]] for x in string_a.split(',')]
dict_a=dict(list_a)
print(dict_a)
Dicts can be instantiated from key, value pairs:
dict_a=dict(x.split('=', 1) for x in string_a.split(','))
List comprehensions are great and all, but they can be difficult to read if overzealous. You can just split it up like follows:
dict_a = dict()
groups = string_a.split(',')
for group in groups:
pair = group.split('=')
key = pair[0]
value = pair[1]
dict_a[key] = value
I'm pretty sure there's a stdlib way to do this same kind of thing, but I can't think of it at the top of my head right now.
Hope this helps!
I want to split a inner string in order to get every item, the string is into a [()] structure,the object to process could be something like:
[(u'|name1|name2|name3|123|124|065|',)]
or
[(u'|name1|',)]
or
[(u'')]
or even
false
To get the items from the string I only need:
mystring.split('|')
But I think that my final approach is ugly and error-prone:
mylist[0][0].split('|')
How can I get a items list in a clean and pythonic way?
I think your approach is correct.
But what about the first and last elements of split('|') result?. They are empty because your strings starts and ends with a '|'.
You could use list comprehension.
[name for name in mylist[0][0].split('|') if name]
Or striping the string before:
mylist[0][0].strip('|').split('|')
Just do some previous checking.
If the string can be nested at not constant depth, just wrap the extraction in a loop until it is instance of basestring.
def split(container):
if not container:
return []
return container[0][0].split('|')
I agree that you're getting the best you can, but if you just want a different (equivalent) way of doing it,
from operator import itemgetter
f = itemgetter(0)
f(f(mylist)).split('|')
I have a dictionary:
a = {"w1": "wer", "w2": "qaz", "w3": "edc"}
When I try to print its values, they are printed from right to left:
>>> for item in a.values():
print item,
edc qaz wer
I want them to be printed from left to right:
wer qaz edc
How can I do it?
You can't. Dictionaries don't have any order you can use, so there's no concept of "left to right" with regards to dictionary literals. Decide on a sorting, and stick with it.
You can use collections.OrderedDict (python 2.7 or newer -- There's an ActiveState recipe somewhere which provides this functionality for python 2.4 or newer (I think)) to store your items. Of course, you'll need to insert the items into the dictionary in the proper order (the {} syntax will no longer work -- nor will passing key=value to the constructor, because as others have mentioned, those rely on regular dictionaries which have no concept of order)
Assuming you want them in alphabetical order of the keys, you can do something like this:
a = {"w1": "wer", "w2": "qaz", "w3": "edc"} # your dictionary
keylist = a.keys() # list of keys, in this case ["w3", "w2", "w1"]
keylist.sort() # sort alphabetically in place,
# changing keylist to ["w1", "w2", w3"]
for key in keylist:
print a[key] # access dictionary in order of sorted keys
as #IgnacioVazquez-Abrams mentioned, this is no such thing as order in dictionaries, but you can achieve a similar effect by using the ordered dict odict from http://pypi.python.org/pypi/odict
also check out PEP372 for more discussion and odict patches.
Dictionaries use hash values to associate values. The only way to sort a dictionary would look something like:
dict = {}
x = [x for x in dict]
# sort here
y = []
for z in x: y.append(dict[z])
I haven't done any real work in python in a while, so I may be a little rusty. Please correct me if I am mistaken.
I wants to search specific value in specific key.
example:
x = [12, {"hello":"world",}]
if x["hello"] == "world":
print "Found!"
My example above is wrong.
What to do?
My example above is wrong. What to do?
Correct it, maybe? Honestly, I feel compelled to link to this:
How to ask questions the smart way?
That being said, the problem is you are trying to index a list with a string, which is not possible. Either do
x[1]["hello"] == "world"
...or simply get rid of the list, there isn't really a reason to use it, anyway. If you want to store additional data, you might as well use the dictionary for that.
You're mixing dictionaries and lists. You probably don't really know how they work.
Lists may have any object you want and are accessed by their position:
>>> x = ['a', 'b', 'c']
>>> x[2]
'c'
Dicts combine hashable objects (non mutable) as keys with values that can be anything. You access a object by it's key (and they aren't kept ordered).
>>> y = {'a':0, 'b':1, 'c':2}
>>> y['c']
>>> 2