I have a set like this.
x = set([u'[{"Mychannel":"sample text"},"p"]'])
I need to convert it into Dict.
I need to get output as
x = {'mychannel':'sampletext'}
How to do this.
It looks like you can unpack that crazy thing like this:
>>> x = set([u'[{"Mychannel":"sample text"}, "p"]'])
>>> lst = list(x)
>>> lst
[u'[{"Mychannel":"sample text"}, "p"]']
>>> lst[0]
u'[{"Mychannel":"sample text"}, "p"]'
>>> inner_lst = eval(lst[0])
>>> inner_lst
[{'Mychannel': 'sample text'}, 'p']
>>> d = inner_lst[0]
>>> d
{'Mychannel': 'sample text'}
However, as #MattDMo suggests in comments, I seriously suggest you re-evaluate this data structure, if not at least to factor out the step where you need eval to use it!
Related
I'm trying to create a byte string, but it seems to be just a regular character string. What am I doing wrong here?
byteStr = b'some string'
byteStr #'some string'
utfStr = 'some string'.encode('utf-8')
utfStr #'some string'
byteStr == utfStr #True
If you're trying to create a byte array in Python 2, it's called a bytearray. Python 2 does not have a byte string.. The b in front of the str is ignored in Python 2, meaning 'hello' == b'hello'
Try this:
>>> f = b'f'
>>> type(f)
<type 'str'>
Now, it's important to remember that u'f' == 'f':
>>> h = u'f'
>>> f == h
True
>>> type(h)
>>> <type 'unicode'>
Is there a short way to assign None or value in a variable, depending on the value?
x= value if value!= 999 else None
result = (on_false, on_true)[condition]
>>> value = 10
>>> x = (None,value)[value != 999]
>>> print x
10
>>> value = 999
>>> x = (None,value)[value != 999]
>>> print x
None
You are using the correct way to do it.
but if you insist on shorten way to figure it out you can use this method:
first way:
{0:value}.get(value==999)
using the trick python saving same hash for False and 0 (hash = 0).
second way:
{999:None}.get(value,value)
using get method and default value to bring this.
third way:
[None, value][value != 999]
when first part stand for value declaration and the second as boolean condition.
My list looks as follow:
items = []
a = "apple", 1.23
items.append(a)
b = "google", 2.33
items.append(b)
c = "ibm", 4.35
items.append(c)
Now I will just remove the row of "apple" by just giving the name of "apple".
How to do?
You can convert items into a dictionary, delete the entry with key apple and return the dictionary items:
>>> items
[('apple', 1.23), ('google', 2.33), ('ibm', 4.35)]
>>> d = dict(items)
>>> del d['apple']
>>> items = d.items()
>>> items
[('ibm', 4.35), ('google', 2.33)]
In python 3, you should cast d.items with list as .items() returns a dict_items object which is iterable but not subscriptable:
>>> items = list(d.items())
I suggest that you use a proper data structure. In your case, a dict will do the trick.
items = {"apple": 1.23, "google": 2.33, "ibm": 4.35}
To delete, use:
items.pop("apple", None)
Since I canonly accept one answer and truely to say I am not 100% satisfied with both, so I haven't accpted any one. Hope it's OK for you all.
I do followings, a combination of both of yours:
d = dict(items)
d.pop("apple", None)
myitem = d.items()
I think the best approach is that of using a dictionary, as suggested by #Sricharan Madasi and #Moses Koledoye. However, provided that the OP seems to prefer to arrange data as a list of tuples, he may find this function useful:
def my_func(lst, key):
return [(name, number) for (name, number) in lst if name != key]
The following interactive session demonstrates its usage:
>>> items = [('apple', 1.23), ('google', 2.33), ('ibm', 4.35)]
>>> my_func(items, 'apple')
[('google', 2.33), ('ibm', 4.35)]
>>> my_func(items, 'ibm')
[('apple', 1.23), ('google', 2.33)]
>>> my_func(items, 'foo')
[('apple', 1.23), ('google', 2.33), ('ibm', 4.35)]
I have a list of tuples like:
>>>list
[('the', 248),
('I', 81),
...
('I', 81)]
I want to take out a specific element like ('to',248), how should I index the element and get it?
>>> l =[('the', 248), ('I', 81), ('I', 81)]
>>> x = [i[1] for i in l]
>>> x
[248, 81, 81]
I'm not sure what you exactly mean by this question, but if you want to take an element out with specific qualities, you would just use index() (no matter the data type):
# x = [("string0",0),("string1",1),("string2",2),("string3",3)]
# Example outputs:
>>> x.index(("string0",0))
0
>>> x.index(("string2",2))
2
I am working on a search algorithm in python but there is something I don't get to work..
I have a list which looks like this [["A","1.txt"],["A","2.txt"],["A","3.txt"],["B","1.txt"],["B","3.txt"]]
Now I want to merge the sub-lists that have the same first index. So the result would be:
[["A",["1.txt","2.txt",3.txt"]],["B",["1.txt"],["3.txt"]]]
Anyone who knows how to do this...
Kinda got a sort (on mergesort basis) but this does not merge the tuples
def merge_pairs(data):
if len(data) <= 1 :
return data[:]
else:
mid = len(data) // 2
fst = merge_pairs(data[:mid])
snd = merge_pairs(data[mid:])
res = []
fi = 0
si = 0
while fi < len(fst) and si < len(snd):
if fst[fi][0] < snd[si][0] or fst[fi][0] == snd[si][0] and fst[fi][1] < snd[si][1]:
res.append(fst[fi])
fi = fi + 1
else:
res.append(snd[si])
si = si + 1
if fi < len(fst) :
res.extend(fst[fi:])
elif si < len(snd) :
res.extend(snd[si:])
return res
So i'd like not to use the dict() function of python
Thanks in advance
The easiest way (which may or may not be slower than the hard way) is to use a defaultdict:
>>> from collections import defaultdict
>>> result = defaultdict(list)
>>> mylist = [["A","1.txt"],["A","2.txt"],["A","3.txt"],["B","1.txt"],["B","3.txt"]]
>>> for key, value in mylist:
... result[key].append(value)
...
>>> print(sorted(result.items()))
[('A', ['1.txt', '2.txt', '3.txt']), ('B', ['1.txt', '3.txt'])]
The hard way (if your data is truly already sorted):
>>> src = [["A","1.txt"],["A","2.txt"],["A","3.txt"],["B","1.txt"],["B","3.txt"]]
>>> prev = None
>>> dst = []
>>> for key, value in src:
... if key != prev:
... prev = key
... dst.append((key, []))
... dst[-1][-1].append(value)
...
>>> print(dst)
[('A', ['1.txt', '2.txt', '3.txt']), ('B', ['1.txt', '3.txt'])]
But note that Python sort is really, really fast, and Python loops like this... Not so much.
Edit According to your comment below, you also want counts. Again there is a dictionary way:
>>> from collections import defaultdict
>>> result = defaultdict(lambda: defaultdict(int))
>>> mylist = [["A","1.txt"],["A","2.txt"],["A", "2.txt"],["A","3.txt"],["B","1.txt"],["B","3.txt"]]
>>> for key, value in mylist:
... result[key][value] += 1
...
>>> print(sorted((x, sorted(y.items())) for (x, y) in result.items()))
[('A', [('1.txt', 1), ('2.txt', 2), ('3.txt', 1)]), ('B', [('1.txt', 1), ('3.txt', 1)])]
and a loop way:
>>> src = [["A","1.txt"],["A","2.txt"],["A", "2.txt"],["A","3.txt"],["B","1.txt"],["B","3.txt"]]
>>> prevkey, prevvalue = None, None
>>> dst = []
>>> for key, value in src:
... if key != prevkey:
... prevkey = key
... prevvalue = None
... dst.append((key, []))
... if value != prevvalue:
... prevvalue = value
... dst[-1][-1].append([value, 0])
... dst[-1][-1][-1][-1] += 1
...
>>> dst
[('A', [['1.txt', 1], ['2.txt', 2], ['3.txt', 1]]), ('B', [['1.txt', 1], ['3.txt', 1]])]
You'd really want to run timeit to be sure, but in this instance, the loop way almost looks guaranteed to be slower (and of course, the dictionary way doesn't require you to do a pre-sort.)