Hi. I have a function in my views in which I have a variable and I use it in template.
imagesj[str(i)]=str(j[0])
from which I get a value similar to this
{'Adele-1-Fuchsia-9': 'product/adele_1_fuchsia_1.jpg',
'Jealyn-37-Brown-10': 'product/jealyn_37_brown_1.jpg'}
I need to get only product/adele_1_fuchsia_1.jpg and product/jealyn_37_brown_1.jpg which are dynamic values and they will be changed according to product. I need to replace the front part before product in string. How can I do this?
I donĀ“t know what your original data structure looks like, but If you have a dictionary like the one below:
dic = {'Adele-1-Fuchsia-9': 'product/adele_1_fuchsia_1.jpg', 'Jealyn-37-Brown-10': 'product/jealyn_37_brown_1.jpg'}
you can get the products-element by iterating the values:
print [x for x in dic.values() if 'product' in x]
this prints:
['product/adele_1_fuchsia_1.jpg', 'product/jealyn_37_brown_1.jpg']
Related
I have a list of dictionaries in which keys are "group_names" and values are gene_lists.
I want to update each dictionary with a new list of genes by looping through a species_list.
Here is my pseudocode:
groups=["group1", "group2"]
species_list=["spA", "spB"]
def get_genes(group,sp)
return gene_list
for sp in species_list:
for group in groups:
gene_list[group]=get_genes(group,sp)
gene_list.update(get_genes(group,sp))
The problem with this code is that new genes are replaced/overwritten by the previous ones instead of being added to the dictionary. My question is where should I put the following line. Although, I'm not sure if this is the only problem.
gene_list.update(get_genes(group,sp))
The data I have looks like this dataframe:
data={"group1":["geneA1", "geneA2"],
"group2":[ "geneB1","geneB2"]}
pd.DataFrame.from_dict(data).T
The data I want to create should look like this:
data={"group1":["geneA1", "geneA2", "geneX"],
"group2":[ "geneB1","geneB2", "geneX"]}
pd.DataFrame.from_dict(data).T
So in this case, "gene_x" refers to the new genes obtained by the get_genes function for each species and finally updated to the existing dictionary.
Any help would be much appreciated!!
You need to append to the list in the dictionary entry, not assign it.
Use setdefault() to provide a default empty list if the dictionary key doesn't exist yet.
for sp in species_list:
for group in groups:
gene_list.setdefault(group, []).extend(get_genes(group, sp))
From what I understand, you want to append new gene to each key, in order to do that:
new_gene = "gene_x"
data={"group1":["geneA1", "geneA2"], "group2":[ "geneB1","geneB2"]}
for value in data.values():
value.append(new_gene)
print(data)
You can also use defaultdict where you can append directly (read the docs for that).
I am using var_dict = defaultdict(list).
Then the key is 'NODE' and value is a list.
I am able to iterate thru the values. But if I want to access elements ['1974'], ['993'],['198']... in this example can you please tell me what what would be the for loop construction for this.
var_dict['NODE']
[[['1013'], ['1974'], ['0/5']], [['1013'], ['993'], ['0/9']], [['9999'], ['198'], ['0/5']], [['9999'], ['992'], ['0/9']]]
I am able to iterate thru dictionary values given a key. My question is, what if I want to access items
for item in node_PS_if_list['IF_PSE2']:
for item1 in item:
will list the respective value. What I need is to access the second element like zz[0][1], zz[1][1], ZZ[2][1] etc.
I would need to increment a variable i and pass it like [i][0], [1][1], [2][1] etc. I would appreciate your assistance to address syntax for this.
var_dict = {'NODE':[[['1013'], ['1974'], ['0/5']], [['1013'], ['993'], ['0/9']], [['9999'], ['198'], ['0/5']], [['9999'], ['992'], ['0/9']]]}
r = [x[1] for x in var_dict['NODE']]
print(r)
Result:
[['1974'], ['993'], ['198'], ['992']]
If you want to iterate over these:
for element in [x[1] for x in var_dict['NODE']]:
# do your thing here
I successfully imported from the web this json file, which looks like:
[{"h_mag":"19.7","i_deg":"9.65","moid_au":"0.035"},{"h_mag":"20.5","i_deg":"14.52","moid_au":"0.028"},
etc ...
I want to extract the values of the key moid_au, later compare moid_au with the key values of h_mag.
This works: print(data[1]['moid_au']), but if I try to ask all the elements of the list it won't, I tried: print(data[:]['moid_au']).
I tried iterators and a lambda function but still has not work yet, mostly because I'm new in data manipulation. It works when I have one dictionary, not with a list of dictionaries.
Thanks in advance for other tips. Some links were confusing.
Sounds like you are using lambda wrong because you need map as well:
c = [{"h_mag":"19.7","i_deg":"9.65","moid_au":"0.035"},{"h_mag":"20.5","i_deg":"14.52","moid_au":"0.028"}]
list(map(lambda rec: rec.get('moid_au'), c))
['0.035', '0.028']
Each lambda grabs a record from your list and you map your function to that.
Using print(data[:]['moid_au']) equals to print(data['moid_au']), and you can see that it won't work, as data has no key named 'moid_au'.
Try working with a loop:
for item in data:
print(item['moid_au'])
using your approach to iterate over the whole array to get all the instances of a key,this method might work for you
a = [data[i]['moid_au']for i in range(len(data))]
print(a)
In which exact way do you want to compare them?
Would it be useful getting the values in a way like this?
list_of_dicts = [{"h_mag":"19.7","i_deg":"9.65","moid_au":"0.035"}, {"h_mag":"20.5","i_deg":"14.52","moid_au":"0.028"}]
mod_au_values = [d["moid_au"] for d in list_of_dicts]
h_mag_values = [d["h_mag"] for d in list_of_dicts]
for key, value in my_list.items ():
print key
print value
for value in my_list.values ():
print value
for key in my_list.keys():
print key
I have a dictionary like such:
dict = {'x':[2,6,4],'y':[56,5,1]}
I would like to pass one of these lists into the query method:
new_df = df.query('col3 == #dict["x"]')
But I get a UndefinedVariableError. Is there any way to do what I want without the roundabout step of setting a new variable and then using "#" with that one
new_v = dict['x']
new_df = df.query('col3 == #new_v')
Do you definetly need the query function?
Otherwise following the example in the query docs you could try something like:
df.loc[df['col3'].isin(dict['x'])]
Note that the isin, might be required since your dictionary returns a list
So you want something like ?
df.query('col3=={}'.format(dict['x']))
If I want to define a function called match_numbers, which would match the area code from one list to the phone number of another list, how should I fix my code? For example:
match_phone(['666', '332'], ['(443)241-1254', '(666)313-2534', '(332)123-3332'])
would give me
(666)313-2534
(332)123-3332
My code is:
def phone (nlist, nlist1):
results = {}
for x in nlist1:
results.setdefault(x[0:3], [])
results[x[0:3]].append(x)
for x in nlist:
if x in results:
print(results[x])
The problem with this code is, however:
It gives me the outputs in brackets, whereas I want it to print
the output line by line like shown above, and
it won't work with the parantheses in the 2nd list (for example
(666)543-2322 must be converted as 666-543-2322 for the list to
work.
Now, there are better/faster approaches to do what you are trying to do, but let us focus on fixing your code.
The first issue you have is how you are slicing your string. Remember that you start at index 0. So if you do:
x[0:3]
What you are actually getting is something like this from your string:
(12
Instead of your intended:
123
So, knowing that indexes start at 0, what you actually want to do is slice your string as such:
x[1:4]
Finally, your line here:
results[x[0:3]].append(x)
There are two problems here.
First, as mentioned above, you are still trying to slice the wrong parts of your string, so fix that.
Second, since you are trying to make a key value pair, what that above line is actually doing is making a key value pair where the value is a list. I don't think you want to do that. You want to do something like:
{'123': '(123)5556666'}
So, you don't want to use the append in this case. What you want to do is assign the string directly as the value for that key. You can do that as such:
results[x[1:4]] = x
Finally, another problem that was noticed, is in what you are doing here:
results.setdefault(x[1:4], [])
Based on the above explanation on how you want to store a string as your value in your dictionary instead of a list, so you don't need to be doing this. Therefore, you should simply be removing that line, it does not serve any purpose for what you are trying to do. You have already initialized your dictionary as results = {}
When you put it all together, your code will look like this:
def match_phone(nlist, nlist1):
results = {}
for x in nlist1:
results[x[1:4]] = x
for x in nlist:
if x in results:
print(results[x])
match_phone(['666', '332'], ['(443)241-1254', '(666)313-2534', '(332)123-3332'])
And will provide the following output:
(666)313-2534
(332)123-3332
If all the phone numbers will be in the format (ddd)ddd-dddd you can use
for number in (num for num in nlist1 if num[1:4] in nlist):
print(number)
You could use some better variable names than nlist and nlist1, in my view.
def match_phone(area_codes, numbers):
area_codes = set(area_codes)
for num in numbers:
if num in area_codes:
print num
You could do something like this:
phone_numbers = ['(443)241-1254', '(666)313-2534', '(332)123-3332']
area_codes = ['666', '332']
numbers = filter(lambda number: number[1:4] in area_codes, phone_numbers)
for number in numbers:
print(number)
Another similar way to do this without using a filter could be something like this:
for number in phone_numbers:
if number[1:4] in area_codes:
print(number)
Output in either case would be:
(666)313-2534
(332)123-3332
No one with regex solution! This may be an option too.
import re
def my_formatter(l1,l2):
mydic = {re.match(r'([(])([0-9]+)([)])([0-9]+[-][0-9]+)',i).group(2):re.match(r'([(])([0-9]+)([)])([0-9]+[-][0-9]+)',i).group(4) for i in l2}
for i in l1:
print "({0}){1}".format(str(i),str(mydic.get(i)))
my_formatter(['666', '332'], ['(443)241-1254', '(666)313-2534', '(332)123-3332'])
It prints-
(666)313-2534
(332)123-3332