I'm trying use ConfigParser with setting of some default values. I know how to set those default values but having trouble with integers.
Here is my code:
import ConfigParser
defaults = {
"str1": "val1",
"str2": "val2",
"int1": 10,
"int2": 20
}
section = "some_section"
config = ConfigParser(defaults)
print config.get(section, "str1")
print config.get(section, "str1")
print config.getint(section, "int1")
print config.getint(section, "int2")
The default values works fine when some of the string values are not being provided.
But, when some of the integers values are not provided and the default value need to be used, exception of TypeError: argument of type 'int' is not iterable being thrown
I didn't found any example of integers as default values. Any help?
So, during my tests I found some interesting stuff.
One of them is that default value for integers and booleans need to be set as strings in the default dictionary (except for None values):
defaults = {
"str1": "val1",
"str2": "val2",
"int1": "10",
"int2": "20",
"boolean1": "True",
"boolean2": "False",
"empty_var": None
}
Note: to extract booleans use ConfigParser.getboolean
Now it works ;)
Related
Sorry for this newbie questions.
I have a dict like this:
{'id':'1', 'Book':'21', 'Member':'3', 'Title':'Chameleon vol. 2',
'Author':'Jason Bridge'}
I want to convert that dict to:
{'id':1, 'Book':21, 'Member':3, 'Title':'Chameleon vol. 2',
'Author':'Jason Bridge'}
I need to convert only the first 3 key value to int
Thanks in advance
dict1 = {'id':'1', 'Book':'21', 'Member':'3', 'Title':'Chameleon vol. 2', 'Author':'Jason Bridge'}
y_dict = dict(list(dict1.items())[:3])
print(y_dict) #dict sliced to the first 3 items that their values will be converted
z_dict = dict(list(dict1.items())[3:])
print(z_dict) #the rest of item that their values will not be converted to integer
x_dict = {k:int(v) for k, v in y_dict.items()}
print(x_dict) # dict values converted to integer
w_dict = {**x_dict, **z_dict}
print(w_dict) # merge of first 3 items with values as integer and the rest of the dict intact
w_dict is the result you are looking for.
Let's say your dict stored in "book_data" variable.
What means first 3 keys?
If you have static keys, you can set manually for it:
for key in ['id', 'Book', 'Member']:
book_data[key] = int(book_data[key])
If you have mutable dictionary, you may get it with it:
for key, val in list(book_data.items())[:3]:
book_data[key] = int(val)
method items help you avoid iterate over values.
I have seen similar questions. This one is the most similar that I've found:
Python converting a list into a dict with a value of 1 for each key
The difference is that I need the dict keys to be unique and ordered keyword arguments.
I am trying to feed the list of links I've generated through a scraper into a request command. I understand the request.get() function only takes a URL string or kwarg parameters - hence my need to pair the list of links with keyword arguments that are ordered.
terms = (input(str('type boolean HERE -->')))
zipcity = (input(str('type location HERE -->')))
search = driver.find_element_by_id('keywordsearch')
search.click()
search.send_keys('terms')
location = driver.find_element_by_id('WHERE')
location.click()
location.send_keys('zipcity')
clickSearch = driver.find_element_by_css_selector('#buttonsearch-button')
clickSearch.click()
time.sleep(5)
cv = []
cvDict = {}
bbb = driver.find_elements_by_class_name('user-name')
for plink in bbb:
cv.append(plink.find_element_by_css_selector('a').get_attribute('href'))
cvDict = {x: 1 for x in cv}
print(cvDict)
SOLVED: (for now). Somehow figured it out myself. That literally never happens. Lucky day I guess!
cvDict = {'one': cv[:1],
'tw': cv[:2],
'thr': cv[:3],
'fou': cv[:4],
'fiv': cv[:5],
'six': cv[:6],
'sev': cv[:7],
'eig': cv[:8],
'nin': cv[:9],
'ten': cv[:10],
'ele': cv[:11],
'twe': cv[:12],
'thi': cv[:13],
'fourteen': cv[:14],
'fifteen': cv[:15],
'sixteen': cv[:16],
'seventeen': cv[:17],
'eighteen': cv[:18],
'nineteen': cv[:19],
'twent': cv[:20],
}
I have a list of unicode elements and I'm trying to remove all integer numbers from It.
My code is:
List = [u'123', u'hello', u'zara', u'45.3', u'pluto']
for el in List:
if isinistance(el, int):
List.remove(el)
The code doesn't work, It give me the same list with u'123' include.
What i need is this:
List = [ u'hello', u'zara', u'45.3', u'pluto']
Can somebody hel me?
You list consists of unicode strings which are no instances of int obviously. You can try converting them to int in a helper function and use this as a condition to remove them/ to construct a new list.
def repr_int(s):
try:
int(s)
return True
except ValueError:
return False
original_list = [u'123', u'hello', u'zara', u'45.3', u'pluto']
list_with_removed_ints = [elem for elem in original_list if not repr_int(elem)]
Suppose I have a list of dictionaries, all of which have the same keys. An instance of such a dictionary in the list might look like:
dict = {"Height": 6.0, "Weight": 201.5, "Name": "John", "Status": "Married"}
Given only a few (key, value) pairs, I want to extract all dictionaries satisfying those pairs. For example, if I have
attributes = {"Height": 5.5, "Name": "John"}
I want to extract all dictionaries whose height value is greater than or equal to 5.5 AND whose name value is John.
I'm able to write the code that can satisfy one OR the other, but dealing with mixed types (float and string) is throwing me off, so my AND operator is being confused I guess. The problem part of my code, for example, is:
for option in attributes.keys():
if dict[option] == attributes[option] and dict[option] >= attributes[option]
print dict
If you have multiple different condition you have to do all of them, but instead of using and you can use all built-in function and a function for filtering the dictionaries, then use it within a list comprehension or filter function in order to get the expected dictionaries.
from operator import itemgetter
option1, option2, option3 = itemgetter(key1, key2, key3)(attributes)
def filter_func(temp_dict):
# key1, key2, key3 have been defined already (keys in attributes)
val1, val2, val3 = itemgetter(key1, key2, key3)(temp_dict)
return all(option1 == val1, option2 => val2, option3 => val3)
filtered_result = filter(filter_func, list_of_dictionaries)
Also note that if it's possible that the dictionaries with your list don't have all the specified keys, the itemgetter might raise an KeyError for getting ride of that you can use dict.get attribute by passing a default value to it (based on your need).
For example for val3 you can use temp_dict.get(key3, 0).
I have converted grid1 and grid2 into arrays and using following function which iterates through table and should return corresponding value form table when grid1 and grid2 values are matched. But somehow the final output contain only 4 integer values which isn't correct. Any suggestion what is possibly wrong here?
def grid(grid1,grid2):
table = {(10,1):61,(10,2):75,(10,3):83,(10,4):87,
(11,1):54,(11,2):70,(11,3):80,(11,4):85,
(12,1):61,(12,2):75,(12,3):83,(12,4):87,
(13,1):77,(13,2):85,(13,3):90,(13,4):92,}
grid3 = np.zeros(grid1.shape, dtype = np.int)
for k,v in table.iteritems():
grid3[[grid1 == k[0]] and [grid2 == k[1]]] = v
return grid3
I think what's happening is that the assignment to the variables "k" and "v" not done using "deepcopy". This means the assignment is just to the variables and not their values. For example, when the value of "k" changes on subsequent iterations, all previous "gridx" assignments now reflect the new/current status of "k".