I'm trying to create the following datastructure (list containing several lists) within a shared dict:
{'my123': [['TEST'],['BLA']]}
code:
records = manager.dict({})
<within some loop>
dictkey = "my123"
tempval = "TEST" # as an example, gets new values with every loop
list = []
list.append(tempval)
if dictkey not in records.keys():
records[dictkey] = [list]
else:
records[dictkey][0].append([tempval])
The first list within the dict element 'my123' gets populated with "TEST", but when I loop a second time (where tempval is "BLA"), the list doesn't get nested.
Instead I'm getting:
{'my123': [['TEST']]}
What am I doing wrong in the else statement?
Edit:
Have modified the code, but still doesn't get added:
records = manager.dict({})
<within some loop>
dictkey = "my123"
tempval = "TEST" # as an example, gets new values with every loop
list = []
list.append(tempval)
if dictkey == "my123":
print tempval # prints new values with every loop to make sure
if dictkey not in records.keys():
records[dictkey] = [list]
else:
records[dictkey].append([list])
Remove the [0] part from the last line. The value in the dictionary is already a list. It is that list you wish to append the second list (['BLA']) to.
You're almost there. You will want to append the list like so:
records = manager.dict({})
# within some loop
dictkey = "my123"
tempval = "TEST" # as an example, gets new values with every loop
temp_list = [tempval] # holds a list of value
if dictkey not in records:
records[dictkey] = [temp_list]
else:
records[dictkey].append(temp_list) # append list of value
I've found the solution. Looks like the append in the else statement doesn't work for class multiprocessing.managers.DictProxy.
I've modified the else statement and now it's working.
records = manager.dict({})
< within some loop >
dictkey = "my123"
tempval = "TEST" # as an example, gets new values with every loop
temp_list = [tempval] # holds a list of value
if dictkey not in records:
records[dictkey] = [temp_list]
else:
records[dictkey] = records.get(dictkey, []) + [temp_list]
Thanks everyone for your help!
Related
Here is my code. I want it to keep adding elements to the list as the user types them.
**while True:
_list = []
new_element = input('typehere:')
_list.append(new_element)
print(_list)**
Here is the output :
typehere:**element_1**
['element_1']
typehere:**element_2**
['element_2']
I want:
typehere:element_1
['element_1']
typehere:element_2
[ 'element_1' , 'element_2' ]
Initialize the list outside the loop:
_list = []
while True:
new_element = input('typehere:')
_list.append(new_element)
print(_list)
Output:
typehere:>? element_1
['element_1']
typehere:>? element_2
['element_1', 'element_2']
Oh. Never mind... I get it now... every time the loop restarts the variable does not save the previous values because I have declared it as an empty list. This code works:
liist = []
while True:
new_element = input('Type here :')
liist.append(new_element)
print(liist)
Ex:
for x in myresult:
y=str(x)
if y.startswith('(') and y.endswith(')'):
y = y[2:-3]
y=y.replace("\\","").replace(";",'')
chr_num = y.find("property_name")
chr_num=chr_num+15
PropertyName = y[chr_num:-1]
chr_num1 = y.find("phrase_value")
chr_num1 = chr_num1 + 14
chr_num2 = y.find("where")
chr_num2=chr_num2-2
PhraseValue = y[chr_num1:chr_num2]
This is the existing code. Now i want to store 'PhraseValue' in dictionary or array.
NOTE: PhraseValue will keep getting values for each iteraction
This is a very basic question. In your case, obviously, PropertyName and PhraseValue are overwritten on each iteration and contains only the last values at the end of the loop.
If you want to store multiple values, the easiest structure is a list.
ret = [] # empty list
for x in some_iterator():
y = some_computation(x)
ret.append(y) # add the value to the list
# ret contains all the y's
If you want to use a dict, you have to compute a key and a value:
ret = {} # empty dict
for x in some_iterator():
y = some_computation(x)
k = the_key(x) # maybe k = x
ret[k] = y # map k to y
# ret contains all the k's and their mapped values.
The choice between a list and a dict depends on your specific problem: use a dict if you want to find values by key, like in a dictionary; use a list if you need ordered values.
Assuming that PropertyName is the key, then you could simply add
results = {}
before the loop, and
results[PropertyName] = PhraseValue
as the last line of the if statement inside the loop.
This solution does have one problem. What if a given PropertyName occurs more than once? The above solution would only keep the last found value.
If you want to keep all values, you can use collections.defaultdict;
import collections
results = collections.defaultdict(list)
Then as the last line of the if statement inside the loop;
results[PropertyName].append(PhraseValue)
I am trying to print out the
exist = False while(exist == False):
try:
name = input('Please enter a file name: ')
myfile = open(name,'r')
a = myfile.readline()
b = myfile.readlines()
count = len(b)
exist = True
except:
print('Error!', name, 'does not exist.')
myfile.close()
# converting input file into dict
lst = list() for term in b:
newterm = term.replace('\n','').split('\t') #replacing with tab
lst.append(newterm)
keylst = list()
vallst = list()
for i in range(len(lst)):
keylst.append(lst[i][0])
vallst.append(lst[i][1])
dict = {}
for i in range(len(lst)):
tempdict = {keylst[i]:vallst[i]}
dict.update(tempdict)
Bunch of code here, user input and so on.
This code is how I formatted the table below.
print('There are', len(dict), 'terms in the new vocabulary list.')
lst = '{0:<5} - {1:>35}'.format(newterm[0], newterm[1])
print(lst)
here saving file
This gives me the output below:
while - Executes a block of code as long as its condition is true.
which prints out only last line/column of my .txt file, but what I want is whole dictionary to print out.
like this:
term definition
break Used to exit a for loop or a while loop1.
continue Used to skip the current block, and return to the "for" or "while" statement
dictionary A mutable associative array (or dictionary) of key and value pairs.
float An immutable floating point number.
immutable Cannot be changed after its created.
int An immutable integer of unlimited magnitude.
pass Needed to create an empty code block
set Unordered set, contains no duplicates
string Can include numbers, letters, and various symbols and be enclosed by either double or single quotes
while Executes a block of code as long as its condition is true.
I tried different ways but none of them worked. please help
You're doing something weird
Instead of
> for i in range(len(lst)):
> keylst.append(lst[i][0])
> vallst.append(lst[i][1])
>
> dict = {} for i in range(len(lst)):
> tempdict = {keylst[i]:vallst[i]}
> dict.update(tempdict)
just use
my_dict=dict(lst)
and don't create variable named dict for it shadows built-in function dict.
The second problem - you don't iterate over your dict, you just output data from newterm. And you need
for term, description in my_dict.items():
print('{0:<5} - {1:>35}'. format(term, description))
I have lists that are empty and filled in the data. I am trying to the store last element of the list into a variable. If there are elements in the list, it is working fine. However, when I pass in a empty [] list, I get error like: IndexError: list index out of range. Which syntax I should be using for []?
ids = [
'abc123',
'ab233',
'23231ad',
'a23r2d23'
]
ids = []
# I tried these for empty
final = [ids if [] else ids[-1]] #error
# final = [ids if ids == None else ids == ids[-1]] # error
# final = [ids if ids == [] else ids == ids[-1]] # gives [[]] instead of []
print(final)
Basically, if an empty list is in ids, I need it to give []. If there are elements, then give the last element, which is working.
Here is one way to do this:
final = ids[-1] if ids else None
(Replace None with the value you'd like final to take when the list is empty.)
you can check for a empty list by below expression.
data = []
if data: #this returns False for empty list
print("list is empty")
else:
print("list has elements")
so what you can do is.
final = data[-1] if data else []
print(final)
final = ids[-1] if len(ids) > 0 else []
This will handle the immediate problem. Please work through class materials or tutorials a little more for individual techniques. For instance, your phrase ids if [] doesnt' do what you (currently) seem to think: it does not check ids against the empty list -- all it does is to see whether that empty list is "truthy", and an empty list evaluates to False.
You are getting the error because you wont be able to select the last item if the list is empty and it will rightfully throw an IndexError.
Try this example
ids = [[i for i in range(10)] for x in range(3)]
ids.append([])
last_if_not_empty = [i[-1] for i in ids if i]
Here you filter out the non-empty list by if i which is the condition to select not empty lists. From there you can pick out the last elements of the lists.
a = list[-1] if not len(list)==0 else 0
Right now I have a for loop that looks one by one for whether the key value == a variable.
I'm doing this one by one by selecting the [0] and [1] index to get the first two children. There could be up to four children, is there a more efficient way to do this than elif?
# INITIALIZE NEW FILTERED DICTIONARY (RETAINING TOP LEVEL ITEMS)
newdata = OrderedDict({k:v for k,v in data.items() if k in ['stop_id', 'stop_name']})
newdata['mode'] = []
arrivalarray = []
# ITERATE CONDITIONALLY KEEPING NEEDED SECTIONS
for i in data['mode']:
if i['route'][0]['route_name'] == line:
if i['route'][0]['direction'][0]['direction_name'] == direction:
for s in i['route'][0]['direction'][0]['trip']:
arrivalarray.append(s['pre_away'])
elif i['route'][0]['direction'][1]['direction_name'] == direction:
for s in i['route'][0]['direction'][1]['trip']:
arrivalarray.append(s['pre_away'])
Well yes, you could use recursion instead of iteration and that is actually what DFS is.
def traverse_json(json, depth):
if depth = 0 :
return [];
else:
data = [];
for i in json.keys():
if isinstance(json[i], dict):
data += traverse_json(json[i], depth -1)
else :
data.append(json[i])
return data
You could start with the max depth you require.
Once you've loaded the JSON data, it's no longer JSON data. It's just a nested series of Python lists, dicts, strings, etc. As such, you can do what you'd do for any Python data structure, such as use a for loop to iterate over the elements of a list:
for d in i['route'][0]['direction']:
if d['direction_name'] == direction:
for s in d['trip']:
arrivalarray.append(s['pre_away'])