I am having values in dict for example
{"AR":True,"VF":False,"Siss":True}
Now I am only extracting the keys having value TRUE, so I am only getting the output AR and Siss, I am trying to save this output in tuple and now wants to print them out in reverse order like ("Siss","AR").
Below is my code snippet, When I convert it into tuple its showing me output in form of character instead of string
for i in dic:
if dic[i]==True:
t = tuple(i)
print (t)
Reverse(t)
def Reverse(tuples):
new_tup = tuples[::-1]
return new_tup
How to change those characters into words/strings ?
You can do it easily by transverse the dictionary in reversed order and filter out the non True values.
d = {'AR': True, 'VF': False, 'Siss': True}
print(tuple(k for k,v in reversed(d.items()) if v is True))
('Siss', 'AR')
Here is a simple step-wise approach that uses a list as an intermediate, fills it with the appropriate keys from your dictionary, reverses the list, then converts it into a tuple.
dic = {"AR":True,"VF":False,"Siss":True}
lst = []
for key in dic:
if dic[key]: (# ==True is redundant)
lst.append(key)
lst.reverse()
result = tuple(lst)
print(result)
#('Siss', 'AR')
A functional approach:
dictionary = { "AR": True, "VF": False, "Siss": True }
filtered = filter(lambda kv: kv[1], reversed(dictionary.items()))
just_key = map(lambda kv: kv[0], filtered)
print(list(just_key))
It works by:
reversed-ing the key-value pairs in the dictionary
filtering the dictionary's items, removing all the key-value pairs that are False.
Just preserving the key with a map
Related
I'm trying to traverse through a dictionary that essentially contains tuples and keys for tuples like this:
(101940039, 'yoel'): 0.0016034940264139383,
(101940039, 'yossi'): 0.004810482079241815,
(101940039, 'youngmen'): 0.0016034940264139383}
I need to access the value of the key, i.e., the string of the tuple. I tried many things, like converting to the dictionary, using key[0] just gives me "'int' object is not subscribable"..
def matching_score(k, tokens, tf_idf_score):
print("Matching Score")
query_weights = {}
for word in tokens:
for key, value in tf_idf_score.items():
**if key in word**:
try:
query_weights[key[0]] += tf_idf_score[key]
except:
query_weights[key[0]] = tf_idf_score[key]
query_weights = sorted(query_weights.items(), key=lambda x: x[1], reverse=True)
print("")
l = []
for i in query_weights[:10]:
l.append(i[0])
print(l)
First, this is a recreation of your data as a dictionary:
d1 = {(101940039, 'yoel'): 0.0016034940264139383,
(101940039, 'yossi'): 0.004810482079241815,
(101940039, 'youngmen'): 0.0016034940264139383}
With keys() it is possible to access the keys. At the same time, we want to convert them into a list.
list(d1.keys())
The result is a list of tuples.
[(101940039, 'yoel'), (101940039, 'yossi'), (101940039, 'youngmen')]
To access individual items in this nested list: first, use the index of the list to select the desired list, and second, use the index of the tuple to select the desired item within.
list(d1.keys())[0][1]
'yoel'
To get all the string elements of the key tuples:
for i in range(len(d1)):
print(list(d1.keys())[i][1])
yoel
yossi
youngmen
I have a list with 2 or 3 character strings with the last character being the same.
example_list = ['h1','ee1','hi1','ol1','b1','ol1','b1']
is there any way to sort this list using the order of another list.
order_list = ['ee','hi','h','b','ol']
So the answer should be something like example_list.sort(use_order_of=order_list)
Which should produce an output like ['ee1','hi1','h1','b1','b1','ol1','ol1']
I have found other questions on StackOverflow but I am still unable find a answer with a good explanation.
You could build an order_map that maps the prefixes to their sorting key, and then use that map for the key when calling sorted:
example_list = ['h1','ee1','hi1','ol1','b1','ol1','b1']
order_list = ['ee','hi','h','b','ol']
order_map = {x: i for i, x in enumerate(order_list)}
sorted(example_list, key=lambda x: order_map[x[:-1]])
This has an advantage over calling order_list.index for each element, as fetching elements from the dictionary is fast.
You can also make it work with elements that are missing from the order_list by using dict.get with a default value. If the default value is small (e.g. -1) then the values that don't appear in order_list will be put at the front of the sorted list. If the default value is large (e.g. float('inf')) then the values that don't appear in order_list will be put at the back of the sorted list.
You can use sorted with key using until the last string of each element in example_list:
sorted(example_list, key=lambda x: order_list.index(x[:-1]))
Ourput:
['ee1', 'hi1', 'h1', 'b1', 'b1', 'ol1', 'ol1']
Note that this assumes all element in example_list without the last character is in order_list
Something like this? It has the advantage of handling duplicates.
sorted_list = [
i
for i, _
in sorted(zip(example_list, order_list), key=lambda x: x[1])
]
I have a Json array which has key value pairs. I want to get value of a particular key in the list. I don't know at what position the key will be in the array so I cant use the index in the array.
How can I get this please? I have tried something like below code to get value of 'filterB' which is 'val1' but no luck. Thanks.
import json
x = '{"filters":[{"filterA":"All"},{"filterB":"val1"}]}'
y = json.loads(x)
w = y['filters']['filterB']
print (w)
w = y['filters']['filterB'] doesn't work because y['filters'] is a list and not dict.
The answer to your question depends on how you want to handle the case of multiple dictionaries inside filters list that have filterB key.
import json
x = '{"filters":[{"filterA":"All"},{"filterB":"val1"}]}'
y = json.loads(x)
# all filterB values
filter_b_values = [x['filterB'] for x in y['filters'] if 'filterB' in x.keys()]
# take first filterB value or None if no values
w = filter_b_values[0] if filter_b_values else None
The source of your data (json) has nothing to do with what you want, which is to find the dictionary in y['filters'] that contains a key called filterB. To do this, you need to iterate over the list and look for the item that fulfils this condition.
w = None
for item in y['filters']:
if 'filterB' in item:
w = item['filterB']
break
print(w) # val1
Alternatively, you could join all dictionaries into a single dictionary and use that like you originally tried
all_dict = dict()
for item in y['filters']:
all_dict.update(item)
# Replace the list of dicts with the dict
y['filters'] = all_dict
w = y['filters']['filterB']
print(w) # val1
If you have multiple dictionaries in the list that fulfil this condition and you want w to be a list of all these values, you could do:
y = {"filters":[{"filterA":"All"},{"filterB":"val1"},{"filterB":"val2"}]}
all_w = list()
for item in y['filters']:
if 'filterB' in item:
all_w.append(item['filterB'])
Or, as a list-comprehension:
all_w = [item['filterB'] for item in y['filters'] if 'filterB' in item]
print(all_w) # ['val1', 'val2']
Note that a list comprehension is just syntactic sugar for an iteration that creates a list. You aren't avoiding any looping by writing a regular loop as a list comprehension
I have a list of alphanumeric strings:
list = ["abc 123", "456 jkl"]
I also have a dictionary that contains substrings of the strings in the list above as keys:
dict = {"abc":"xyz", "jkl":"stu"}
I want to update the list using the dictionary so that the result looks like:
result = ["xyz 123", "456 stu"]
Basically, I want to replace any component (and only that component) in the list that matches dictionary keys with dictionary values.
I tried iterating through the dictionary + the list to do so, but I am having trouble updating just the substring. I would also like to learn more efficient/pythonic way of achieving this, please.
for element in list:
for key,value in dictionary.items():
if key in element:
element = value
If you are prepared to use regex:
>>> import re
>>> result = re.sub(
r'\b'+r'|\b'.join(dct)+r'\b',
lambda m: dct.get(m.group(), m.group()),
','.join(lst)
).split(',')
# or
>>> result = [re.sub(
r'\b'+r'|\b'.join(dct)+r'\b',
lambda m: dct.get(m.group(), m.group()),
item
) for item in lst]
>>> result
["xyz 123", "456 stu"]
Where,
r'\b'+r'|\b'.join(dct)+r'\b' joins keys of dct with delimter | to form the pattern string.
lambda m: dct.get(m.group(), m.group()) creates a callable, that, if match found, returns value for that matching key from dct else returns the match as is.
','.join(lst) and .split(',') is a way to do this without a loop, only if your strings do not contain comma, otherwise some other delimiter can be used.
is like this? you must create a new list (based on your code)
list = ["abc 123", "456 jkl"]
dict = {"abc":"xyz", "jkl":"stu"}
newDict = []
for element in list:
for key,value in dict.items():
if key in element:
newElement = element.replace(key, value)
newDict.append(newElement)
print newDict
You might get the result with list comprehension and replace() method like below -
l = ["abc 123", "456 jkl"]
d = {"abc":"xyz", "jkl":"stu"}
l = [e.replace(key, val) for e in l for key, val in d.items() if key in e]
print(l)
Simple loop will do as well.
But remember in this solution if any key of the dictionary present as part of the word that will be replaced as well. If you don't want that then you can split the elements of the list first to get the result. Or you can use regex to do that
I have a dictionary where the values are a list of tuples.
dictionary = {1:[('hello, how are you'),('how is the weather'),('okay
then')], 2:[('is this okay'),('maybe It is')]}
I want to make the values a single string for each key. So I made a function which does the job, but I do not know how to get insert it back to the original dictionary.
my function:
def list_of_tuples_to_string(dictionary):
for tup in dictionary.values():
k = [''.join(i) for i in tup] #joining list of tuples to make a list of strings
l = [''.join(k)] #joining list of strings to make a string
for j in l:
ki = j.lower() #converting string to lower case
return ki
output i want:
dictionary = {1:'hello, how are you how is the weather okay then', 2:'is this okay maybe it is'}
You can simply overwrite the values for each key in the dictionary:
for key, value in dictionary.items():
dictionary[key] = ' '.join(value)
Note the space in the join statement, which joins each string in the list with a space.
It can be done even simpler than you think, just using comprehension dicts
>>> dictionary = {1:[('hello, how are you'),('how is the weather'),('okay then')],
2:[('is this okay'),('maybe It is')]}
>>> dictionary = {key:' '.join(val).lower() for key, val in dictionary.items()}
>>> print(dictionary)
{1: 'hello, how are you how is the weather okay then', 2: 'is this okay maybe It is'}
Now, let's go through the method
we loop through the keys and values in the dictionary with dict.items()
assign the key as itself together with the value as a string consisting of each element in the list.
The elemts are joined together with a single space and set to lowercase.
Try:
for i in dictionary.keys():
dictionary[i]=' '.join(updt_key.lower() for updt_key in dictionary[i])