Dictionary access is stopping the code flow - python

I have a 3 seperate dictionaries that I manually enter values into. There is a loop that shows the value associated with the keys depending on a if condition
inv_dict_celltype and buf_dict_celltype are dictioanries. From the code below i observe that when i try to access both the dictionaries in different scenarios the code doesn't work. The output I get shows the dictionary values present in the first statement I give here, I get all the values in inv_dect_celltype but it doesn't proceed with next if statement, instead comes out
And the temp_list contains the following data :
temp_list = {'INV_X20B_NXP7P5PP96PTL_C16', 'INV_X6B_NXP7P5PP96PTL_C16',
'INV_X8B_NXP7P5PP96PTL_C16', 'INV_X16B_NXP7P5PP96PTL_C16',
'INV_X10B_NXP7P5PP96PTL_C16', 'BUF_X6N_A7P5PP96PTL_C16',
'BUF_X20N_A7P5PP96PTL_C16', 'BUF_X8N_A7P5PP96PTL_C16',
'BUF_X10N_A7P5PP96PTL_C16', 'BUF_X7N_A7P5PP96PTL_C16',
'BUF_X1P3N_A7P5PP96PTS_C18'}
for each_cell in temp_list:
if each_cell.startswith('INV_'):
print(inv_dict_celltype[each_cell])
if each_cell.startswith('BUF_'):
print(buf_dict_celltype[each_cell])

I am not sure what exactly you want to retrieve from your dictionaries, and how the other two dictionaries look like, but try with the following.
for each_cell in temp_list:
if each_cell.startswith('INV_'):
for i in inv_dict_celltype:
if i == each_cell:
print(i)
if each_cell.startswith('BUF_'):
for x in buf_dict_celltype:
if x == each_cell:
print(x)

Related

Unable to store values in an array from for loop in python

First I tried directly storing values from a list having the name 'data' in an array variable 'c' using loop but 'none' got printed
for i in data:
print(i['name'])
c=i['name']
Here print(i['name']) perfectly worked and output appeared
This is the working ouput
Then I printed c in order to print the values generated using loop. The ouput came as none.
print(c)
Then I tried another way by storing the values and making the array iterable at the same time using for loop. An error occurred which I was unable to resolve.
for i in data:
b[c]=i['name']
c=c+1
The error apeared is as follow-
I have tried two ways, if there is any other way please help me out as I am new to python.
It looks like the variable 'data' is a dictionary.
If you want to add each name from that dictionary to a list:
# create a new list variable
names = []
for i in data:
name = i['name']
print(name)
# add the name to the list
names.append(name)
# output the new list
print(names)
Assuming your data object here is a list like [{"name": "Mr. Green", ...}, {"name": "Mr. Blue", ...}].
If your goal is to end up with c == ["Mr. Green", "Mr. Blue"], then you're looking for something like:
c = []
for i in data:
c.append(i['name'])
print(c)
or you can accomplish tasks like these using list comprehensions like:
c = [i['name'] for i in data]
print(c)
The first code example you posted is iterating through the items in data and reassigning the value of c to each item's name key - not adding them to a list("array"). Without knowing more about the code you ran to produce the screenshot and/or the contents of data, it's hard to say why you're seeing print(c) produce None. I'd guess the last item in data is something like {"name": None, ...} which if it's coming from JSON is possible if the value is null. Small note: I'd generally use .get("name") here instead so that your program doesn't blow up if an item is missing a "name" key entirely.
For your second code example, the error is different but I think falls along a similar logical fallacy which is that lists in python function differently from primitives(things like numbers and strings). For the interpreter to know that b or c are supposed to be lists("arrays"), they need to be instantiated differently and they have their own set of syntax/methods for mutation. For example, like arrays in other languages, lists are indexed by position so doing b[c] = <something> will only work if c is an integer. So something similar to your second example that would also produce a list of names like my above would be:
b = [None] * len(data)
c = 0
for i in data:
b[c]=i['name']
c=c+1
Note that if you only initialize b = [], you get an IndexError: list assignment index out of range on the initial assignment of b[0] = "some name" because the list is of size 0.
Add
b = []
above your first line of code. As the error is saying that you have not (and correctly so) defined the list to append.
I personally would use list comprehension here
b = [obj['name'] for obj in data]
where obj is i as you have defined it.

How to call a specific item in a list subject to another list

I'm just a beginner for python and i wanted to challenge myself so i created a database as a list containing id,password lists such as:
database =[['hosni', '66741'], ['merdali', 'mkemal'], ['ahmet', '123'], ['ahmethan', '6669']]
I'd like to know an id's index number in the database, so i tried this:
for i in range(len(database)):
if database[i].index('merdali')==0:
print(i)
However i get this: error:ValueError: 'merdali' is not in list
The point is that should not the program run the entire lists independently and check whether the condition is satisfied or not, if so, print the "i" value I demand?
if the code had worked properly, i would have written the following to access to the password:
database[1][1]=='mkemal'
thank you for your helps already!
You could use a list comprehension to separate out the ids and then use .index() on the newly created list
[item[0] for item in database].index("merdali")
To follow your structure while you get to more advanced subjects,
>>> for i, x in enumerate(database):
... if x[0] == 'merdali':
... print(i)
... break
...
1
>>>
It's as simple as a next() comprehension:
index = next(l[1] for l in database if l[0] == "hosni")
By the way, a dictionary is a way more suitable choice for your database.

Dynamically building a dictionary based on variables

I am trying to build a dictionary based on a larger input of text. From this input, I will create nested dictionaries which will need to be updated as the program runs. The structure ideally looks like this:
nodes = {}
node_name: {
inc_name: inc_capacity,
inc_name: inc_capacity,
inc_name: inc_capacity,
}
Because of the nature of this input, I would like to use variables to dynamically create dictionary keys (or access them if they already exist). But I get KeyError if the key doesn't already exist. I assume I could do a try/except, but was wondering if there was a 'cleaner' way to do this in python. The next best solution I found is illustrated below:
test_dict = {}
inc_color = 'light blue'
inc_cap = 2
test_dict[f'{inc_color}'] = inc_cap
# test_dict returns >>> {'light blue': 2}
Try this code, for Large Scale input. For example file input
Lemme give you an example for what I am aiming for, and I think, this what you want.
File.txt
Person1: 115.5
Person2: 128.87
Person3: 827.43
Person4:'18.9
Numerical Validation Function
def is_number(a):
try:
float (a)
except ValueError:
return False
else:
return True
Code for dictionary File.txt
adict = {}
with open("File.txt") as data:
adict = {line[:line.index(':')]: line[line.index(':')+1: ].strip(' \n') for line in data.readlines() if is_number(line[line.index(':')+1: ].strip('\n')) == True}
print(adict)
Output
{'Person1': '115.5', 'Person2': '128.87', 'Person3': '827.43'}
For more explanation, please follow this issue solution How to fix the errors in my code for making a dictionary from a file
As already mentioned in the comments sections, you can use setdefault.
Here's how I will implement it.
Assume I want to add values to dict : node_name and I have the keys and values in two lists. Keys are in inc_names and values are in inc_ccity. Then I will use the below code to load them. Note that inc_name2 key exists twice in the key list. So the second occurrence of it will be ignored from entry into the dictionary.
node_name = {}
inc_names = ['inc_name1','inc_name2','inc_name3','inc_name2']
inc_ccity = ['inc_capacity1','inc_capacity2','inc_capacity3','inc_capacity4']
for i,names in enumerate(inc_names):
node = node_name.setdefault(names, inc_ccity[i])
if node != inc_ccity[i]:
print ('Key=',names,'already exists with value',node, '. New value=', inc_ccity[i], 'skipped')
print ('\nThe final list of values in the dict node_name are :')
print (node_name)
The output of this will be:
Key= inc_name2 already exists with value inc_capacity2 . New value= inc_capacity4 skipped
The final list of values in the dict node_name are :
{'inc_name1': 'inc_capacity1', 'inc_name2': 'inc_capacity2', 'inc_name3': 'inc_capacity3'}
This way you can add values into a dictionary using variables.

How to iterate to create variables in a list

Suppose I have the following code:
classifiers_name_all = [('AdaBoostClassifier', AdaBoostClassifier(), 'AdaBoost'),
('BernoulliNB', BernoulliNB(), 'Bernoulli Naive Bayes'),
('DummyClassifier', DummyClassifier(), 'Dummy Classifier')]
clf_values = []
for clf_na in classifiers_name_all:
clf_values.append((locals()['score_'+clf_na[0]+'_mean'], locals()['score_'+clf_na[0]+'_stddev']))
clf_values
The code above doesn't quite work.
I want to get a list which contains the variables:
clf_values = [(score_AdaBoostClassifier_mean, score_AdaBoostClassifier_stddev),
(score_BernoulliNB_mean, score_BernoulliNB_stddev)
(score_DummyClassifier_mean, score_DummyClassifier_stddev)]
How do I do this? Many thanks.
From whatever info you have given so far, I infer that there are no key errors and the resultant list is a list containing nones.
This can only mean, that your code works fine but the variables u are trying to access have 'None' values assigned to them. Check why your values are having None values and once that is fixed, this list will get desired values.

Making several wordclouds out of list of dictionaries

I have a list of dictionaries in union_dicts. To give you an idea it's structured as follows
union_dicts = [{'bla' : 6, 'blub': 9}, {'lub': 20, 'pul':12}]
(The actual lists of dicts is many times longer, but this is to give the idea)
For this particular list of dictionaries I want to make a wordcloud. The function that makes a wordcloud is as follows (nothing wrong with this one):
def make_words(words):
return ' '.join([('<font size="%d">%s</font>'%(min(1+words[x]*5/max(words.values()), 5), x)) for x in words])
Now I have written the following code that should give every dictionary back. Return gives only the first dictionary back in the following function below:
def bupol():
for element in union_dicts:
return HTML(make_words(element))
bupol()
I have already tried to simply print it out, but then I simply get ''Ipython display object'' and not the actual display. I do want the display. Yield also doesn't work on this function and for some reason using list = [] along with list.apped() return list instead of returning in the current way also doesn't work. I'm quite clueless as how to properly iterate over this so I get a display of every single dictionary inside union_dicts which is a list of dictionaries.
How about something like this?
def bupol():
result = []
for element in union_dicts:
result.append(HTML(make_words(element)))
return result

Categories

Resources