proper formatting printing the length of items in a dictionary - python-2.7

My code seems to be working, but I have having trouble with the print statement, which I will eventually write out to a CSV. I am able to get the print to work for the first two items, but when I try to add the len part as the third thing to print, it get an error "'str' object is not callable". When I print the len part by itself, it seems to work fine. Any insight as to what I am doing wrong to print all together?
inFile = open(file.txt,'r')
reader = csv.reader(inFile)
allrows = list(reader)
dd = defaultdict(OrderedDict)
ids = OrderedDict()
output = {}
iterallrows = iter(allrows)
next(iterallrows)
for row in iterallrows:
id_ = row[2]
name = row[3]
dd[id_][name] = None
ids[id_] = None
print('{} {} {}'.format(id_,','.join(dd[id_],','(len(dd[id_])))))

You have this:
[...],','(...)[...]
This attempts to treat ',' as a function, which it is not. Put a comma between all arguments to a function.

Related

Declaring an object within (vs. outside) a while loop

Given the python 2.7 code below:
# faultReportObj = {}
flatDataObj = []
while row:
faultReportObj = {}
faultReportObj['MessageTime'] = row['MessageTime']
faultReportObj['Event'] = row['Event']
faultReportObj['Subsystem'] = row['Subsystem']
faultReportObj['UnifiedFaultCode'] = row['UnifiedFaultCode']
faultReportObj['FaultDescription'] = row['FaultDescription']
faultReportObj['FaultDetails'] = row['FaultDetails']
faultReportObj['FirstOccurrenceDateTime'] = row['FirstOccurrenceDateTime']
faultReportObj['LastOccurrenceDateTime'] = row['LastOccurrenceDateTime']
faultReportObj['OccurrenceCount'] = row['OccurrenceCount']
print "current row:"
pp.pprint(faultReportObj)
flatDataObj.append(faultReportObj)
row = cursor.fetchone()
conn.close()
pp.pprint(flatDataObj)
If I declare faultReportObj outside the while loop, I get (say) 96 entries in flatDataObj that are all identical to the very last row returned by the query. Note that the pprint statement within the while loop prints the expected (varying) results.
If, as above, I declare faultReportObj inside the loop, flatDataObj is loaded correctly.
Why???? Why is the very last row returned being propagated throughout the entire list?
Thanks!
This is due to list.append inserting a reference to faultReportObj and not copying the value of the dict.
Another way of looking at it:
If you define faultReportObj before the loop, the following occurs:
Create a new dict.
Populate it.
Append a reference to the dict into the list.
Change the dict's content.
Append another reference to the same dict.
etc.
Here's a short piece of code that exemplifies this property:
>>> d = {}
>>> l = []
>>> l.append(d)
>>> d[1] = 2
>>> l
[{1: 2}]
What you want is for step one (Create a new dict) to happen in every iteration of the loop, so that you append a different dict every time.

Creating a Dictionary from a while loop (Python)

How can I create a Dictionary from my while loop below? infile reads from a file called input, which has the following content:
min:1,23,62,256
max:24,672,5,23
sum:22,14,2,3,89
P90:23,30,45.23
P70:12,23,24,57,32
infile = open("input.txt", "r")
answers = open("output.txt", "w")
while True:
line = infile.readline()
if not line: break
opType = line[0:3]
numList = (line[4:len(line)])
numList = numList.split(',')
What I'm trying to do is basically 2 lists, one that has the operation name (opType) and the other that has the numbers. From there I want to create a dictionary that looks like this
myDictionary = {
'min': 1,23,62,256,
'max': 24,672,5,23,
'avg': 22,14,2,3,89,
'P90': 23,30,45.23,
'P70': 12,23,24,57,32,
}
The reason for this is that I need to call the operation type to a self-made function, which will then carry out the operation. I'll figure this part out. I currently just need help making the dictionary from the while loop.
I'm using python 2.7
Try the following code.
I believe, you would need the 'sum' also in the dictionary. If not, just add a condition to remove it.
myDictionary = {}
with open('input.txt','r') as f:
for line in f:
x = line.split(':')[1].rstrip().split(',')
for i in xrange(len(x)):
try:
x[i] = int(x[i])
except ValueError:
x[i] = float(x[i])
myDictionary[line.split(':')[0]] = x
print myDictionary

How do I reformat the output of re.findall?

Here is my code:
def cost_channelID(received_frame):
received_frame.columns = ['Ad', 'Impressions', 'eCPM', 'Ad Spend']
Ads = received_frame['Ad']
ID = []
for ad in Ads:
num = re.findall(r'\d{6}',ad)
ID.append(num)
ID = pd.Series(ID)
return(ID)
The output is like this:
[111234]
[111235]
......
[111444]
I would like the output to be without the brackets:
111234
111235
......
144444
Getting single element from sequence in Python is fairly simple
num = re.findall(r'\d{6}',ad)[0]
Although I'd think about why re.findall (method that returns sequence) was used in first place.

''str' object does not support item assignment' python 2

So this is my code it is strying tomease car registration plates, start times and end times (In the complete code it would be printed at the bottom).
data = str(list)
sdata = str(list)
edata = str(list)
current = 0
repeats = input ('How many cars do you want to measure?')
def main():
global current
print (current)
print ''
print ''
print '---------------------------------------'
print '---------------------------------------'
print 'Enter the registration number.'
data[current] = raw_input(' ')
print 'Enter the time it passed Camera 1. In this form HH:MM:SS'
sdata[current] = raw_input(' ')
print 'Enter the time it passed Camera 2. In this form HH:MM:SS'
edata[current] = raw_input (' ')
print '---------------------------------------'
print''
print''
print''
print 'The Registration Number is :'
print data[current]
print''
print 'The Start Time Is:'
print sdata[current]
print''
print 'The End Time Is:'
print edata[current]
print''
print''
raw_input('Press enter to confirm.')
print'---------------------------------------'
d = d + 1
s = s + 1
a = a + 1
current = current = 1
while current < repeats:
main()
When I run it and it gets to:
data[current] = raw_input(' ')
I get the error message 'TypeError: 'str' object does not support item assignment'
Thank you in advance for the help. :D
The error is clear. str object does not support item assignment
Strings in python are immutable. You have converted the data to a string when you do
data = str(list)
So, by
data["current"] = raw_input()
you are trying to assign some value to a string, which is not supported in python.
If you want data to be a list,
data = list()
or
data = []
will help, thus preventing the error
Dont use str during assignment
data = str(list)
sdata = str(list)
edata = str(list)
Instead use
data = []
sdata = []
edata = []
and later while printing use str if u want
print str(data[current])
as aswin said its immutable so dont complex it

Multidict in python not working ?? How to create it?

I want to create an python multi dimensional dictionary :-
Currently i am doing like this
multidict = {}
IN LOOP
mulitdict[i] = data
if loop runs ten times I am getting same value in all index..
Eg:
I want to have like this
multidict {0 : {'name':name1, 'age' : age1}, 1: {'name':name2, 'age' : age2}
but i am getting as shown below
multidict {0 : {'name':name1, 'age' : age1}, 1: {'name':name1, 'age' : age1}
I also tried the default dict also....but every time i get same value in all index. What is the problem?
Tried code :
csv_parsed_data2 = {}
with open('1112.txt') as infile:
i =0
for lineraw in infile:
line = lineraw.strip()
if 'sample1 ' in line:
### TO GET SOURCE ROUTER NAME ###
data['sample1'] = line[8:]
elif 'sample2- ' in line:
### TO GET DESTINATION ROUTER NAME ###
data['sample2'] = line[13:]
elif 'sample3' in line:
### TO GET MIN,MAX,MEAN AND STD VALUES ###
min_value = line.replace("ms"," ")
min_data = min_value.split(" ")
data['sample3'] = min_data[1]
csv_parsed_data2[i] = data
i = i + 1
print i,'::',csv_parsed_data2,'--------------'
print csv_parsed_data2,' all index has same value'
any efficient way to do this??
It sounds you are assigning the same data dict to each of the values of your outer multidict, and just modifying the values it holds on each pass through the loop. This will result in all the values appearing the same, with the values from the last pass through the loop.
You probably need to make sure that you create a separate dictionary object to hold the data from each value. A crude fix might be to replace multidict[i] = data with multidict[i] = dict(data), but if you know how data is created, you can probably do something more elegant.
Edit: Seeing your code, here's a way to fix the issue:
csv_parsed_data2 = {}
with open('1112.txt') as infile:
i =0
data = {} # start with empty data dict
for lineraw in infile:
line = lineraw.strip()
if 'sample1 ' in line:
### TO GET SOURCE ROUTER NAME ###
data['sample1'] = line[8:]
elif 'sample2- ' in line:
### TO GET DESTINATION ROUTER NAME ###
data['sample2'] = line[13:]
elif 'sample3' in line:
### TO GET MIN,MAX,MEAN AND STD VALUES ###
min_value = line.replace("ms"," ")
min_data = min_value.split(" ")
data['sample3'] = min_data[1]
csv_parsed_data2[i] = data
data = {} # after saving a reference to the dict, reinitialize it
i = i + 1
print i,'::',csv_parsed_data2,'--------------'
print csv_parsed_data2,' all index has same value'
To understand what was going on, consider this simpler situation, where I a values in a dictionary after saving a reference to it when it had some older values:
my_dict = { "foo": "bar" }
some_ref = my_dict
print some_ref["foo"] # prints "bar"
my_dict["foo"] = "baz"
print some_ref["foo"] # prints "baz", since my_dict and some_ref refer to the same object
print some_ref is d # prints "True", confirming that fact
In your code, my_dict was data and some_ref were all the values of csv_parsed_data2. They would all end up being references to the same object, which would hold whatever the last values assigned to data were.
Try this:
multidict = {}
for j in range(10):
s = {}
s['name'] = raw_input()
s['age'] = input()
multidict[j] = s
This will have the desired result