INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Dictionary into a table format - Python

Dictionary into a table format - Python

(OP)
Hello everyone,

I am having some problems trying to print the following dictionary:

{('31', '3'): '2.85124e-05', ('31', '23'): '2.85124e-05', ('31', '17'): '2.85124e-05', ('31', '30'): '2.85124e-05', ('31', '19'): '2.85124e-05', ('31', '31'): '2.85124e-05', ('31', '26'): '2.85124e-05', ('31', '10'): '2.85124e-05', ('31', '7'): '2.85124e-05', ('31', '22'): '2.85124e-05', ('31', '12'): '2.85124e-05', ('31', '25'): '2.85124e-05', ('31', '5'): '2.85124e-05', ('31', '8'): '2.85124e-05', ('31', '21'): '2.85124e-05', ('31', '14'): '2.85124e-05', ('31', '16'): '2.85124e-05', ('31', '1'): '2.85124e-05', ('31', '18'): '2.85124e-05', ('31', '24'): '2.85124e-05', ('31', '6'): '2.85124e-05', ('31', '15'): '2.85124e-05', ('31', '11'): '2.85124e-05', ('31', '29'): '2.85124e-05', ('31', '4'): '2.85124e-05', ('31', '13'): '2.85124e-05', ('31', '27'): '2.85124e-05', ('31', '2'): '2.85124e-05', ('31', '9'): '2.85124e-05', ('31', '20'): '2.85124e-05', ('31', '28'): '2.85124e-05'}

into a tabular format.

I would like that the first two keys of the dictionary are the indices of a matrix (the first one is the row number and the second is the column number) and the value is the matrix value.
Anyone has an idea how to print this into a table/matrix with 31 rows x 31 columns, where the 31st row is something like:

2.85124e-05
2.85124e-05
2.85124e-05
2.85124e-05
2.85124e-05
2.85124e-05
2.85124e-05
2.85124e-05
...
2.85124e-05

? Thank you very much for your help!

RE: Dictionary into a table format - Python

You can try something like this:

CODE

dic = {(1,1):'a', (1,2):'b', (1,3):'c',
       (2,1):'t', (2,2):'u', (2,3):'v'}

print "dictionary:"
print dic

print "matrix:"
rows = 2
col = 3
for i in range(1, rows+1):
  for j in range(1, col+1):
    # print line
    print dic[(i, j)],
  # \n
  print 

Output:

CODE

dictionary:
{(1, 2): 'b', (1, 3): 'c', (2, 1): 't', (2, 3): 'v', (2, 2): 'u', (1, 1): 'a'}
matrix:
a b c
t u v 

RE: Dictionary into a table format - Python

to access the dictionary value you can use dic[i, j] (instead of dic[(i, j)])

RE: Dictionary into a table format - Python

(OP)
Hello Mikrom,

Thank you very much for your reply, could you also help me to get the number of rows and columns of a dictionary?
How do I do that? I am used to do "size(matrix)" in matlab to get this information.

Thank you!

RE: Dictionary into a table format - Python

Ok,
we can get a list of all keys from dictionary - its for my example this
[(1, 2), (1, 3), (2, 1), (2, 3), (2, 2), (1, 1)]

Then from it extract all row-indices , it's first components from (., .) - i.e.:
[1, 1, 2, 2, 2, 1]
and similarly col-indices, it's second components from (., .) - i.e.:
[2, 3, 1, 3, 2, 1]
and then when we take the maximum of the list we will get number of matrix rows and columns. For my example it's 2 x 3 matrix.

The code is here:

CODE

dic = {(1,1):'a', (1,2):'b', (1,3):'c',
       (2,1):'t', (2,2):'u', (2,3):'v'}

print "dictionary:"
print dic

print "list of dictionary keys:"
dic_keys = dic.keys()
print dic_keys

list_of_row_indices = [key[0] for key in dic_keys ]
print list_of_row_indices
list_of_col_indices = [key[1] for key in dic_keys ]
print list_of_col_indices

rows = max(list_of_row_indices)
cols = max(list_of_col_indices)
print "matrix (%d x %d):" % (rows, cols)
for i in range(1, rows+1):
  for j in range(1, cols+1):
    # print line
    #print dic[(i, j)],
    print dic[i, j],
  # \n
  print 

RE: Dictionary into a table format - Python

I forgot to post the output of the example above - its:

CODE

C:\Work>python dic2tab.py
dictionary:
{(1, 2): 'b', (1, 3): 'c', (2, 1): 't', (2, 3): 'v', (2, 2): 'u', (1, 1): 'a'}
list of dictionary keys:
[(1, 2), (1, 3), (2, 1), (2, 3), (2, 2), (1, 1)]
[1, 1, 2, 2, 2, 1]
[2, 3, 1, 3, 2, 1]
matrix (2 x 3):
a b c
t u v 

RE: Dictionary into a table format - Python

(OP)
Thank you for your posts, but in my python version the command:

>>print dic[i, j],

does not work.
I think I need to write something like this: print(dic[i,j]+",")

RE: Dictionary into a table format - Python

I'm using Python 2.x
Look at your version with

CODE

python --version 
When you have Python 3.x, then it doesn't have statement print but the function print()
Then instead of

CODE

print dic[i, j], 

try to use

CODE

print(dic[i, j], end=" ") 
Look here
https://docs.python.org/3.0/whatsnew/3.0.html

RE: Dictionary into a table format - Python

(OP)
I am using python 3.3, but I don't have access to libraries like "numpy" and so. - Company policy

Here is my code. Unfortunately I am not having the same result as you had:

CODE --> python

def main():
        file_object=open('out_matrix2.txt','r')
        x=[]
        y=[]
        z=[]
        for line in file_object:
                ax=line.split(",")[0]
                ay=line.split(",")[1]
                az=line.split(",")[2]
                x.append(int(ax))
                y.append(int(ay))
                z.append(az.rstrip())
        nx=len(x)
        ny=len(y)
        nz=len(z)
        i=1
        j=1
        k=1
        dict={}
        matrix=[]
        for i in range(nx):
                for j in range(ny):
                        dict[int(x[i]),int(y[j])]=z[i]
        print(dict)
        dict_keys=dict.keys()

        list_of_row_indices=[key[0] for key in dict_keys]
        list_of_col_indices=[key[1] for key in dict_keys]

        rows=max(list_of_row_indices)
        cols=max(list_of_col_indices)
        print("matrix (%d x %d)" %(rows,cols))
        for i in range(1, rows):
                for j in range(1, cols):
                        print(dict[x[i],y[j]]+",")
                print(' \n')
if __name__ == '__main__':
        main() 

RE: Dictionary into a table format - Python

(OP)
Sorry but I need to use python 3.3, it is sadly mandatory =(

RE: Dictionary into a table format - Python

Quote (nvhuser)


Unfortunately I am not having the same result as you had

What is your input data and what's your result ?

When I look at your code, then for example

CODE

>>> rows = 5 
>>> for i in range (1, rows):
... 	print i
... 
1
2
3
4 
Therefore If you want to iterate i=1,..,rows you need to do

CODE

>>> for i in range (1, rows+1):
... 	print i
... 
1
2
3
4
5 

RE: Dictionary into a table format - Python

(OP)
As attachment to this post, follows my inputdata.
What I would like to have is a matrix 31x31 with zeros and using the information in "out_matrix2.txt" populate the matrix (substitute the value "0" for the value that is specified by the txt file).
I think I am not going in the correct direction...

If the file "out_matrix2.txt" has the following information:

1,1,2.1
1,4,0.1
3,2,0.4

The script should extract the maximum value in the first key and the value in the second key, i.e., 3 and 4, respectively. Then, it create a matrix 3x4 with zeros. After that, using the data available in the file "out_matrix2.txt", the output should be:


2.1,0.0,0.0,0.1
0.0,0.0,0.0,0.0
0,0,0.4,0.0,0.0

That is exactly what I am needing. I have seen that is very easy using "numpy" library, but I cant use it.
Thank you very much for your support!

RE: Dictionary into a table format - Python

Quote (nvhuser)


Sorry but I need to use python 3.3, it is sadly mandatory =(
Sorry, but I have not Python 3.x, because the production code I have written still runs on the version 2.7.x, but I hope that you will be able to convert this example without any problems:

So I have this data file:
matrix.txt

CODE

1,1,2.1
1,4,0.1
3,2,0.4 

and this source:
dic2tab.py

CODE

# set DebugInfo True or False
DBG = False
# read data from a file into dictionary
sep = ","
dic ={}
for line in open('matrix.txt'):
  # when line not empty
  if line.strip():
    # remove \n
    line = line.strip()
    # split line into list
    lst = line.split(sep)
    if DBG: print lst
    # populate dictionary
    x = int(lst[0])
    y = int(lst[1])
    z = float(lst[2])
    dic[x, y] = z

# print dictionary
if DBG: 
  print "dictionary:"
  print dic

if DBG: print "list of dictionary keys:"
dic_keys = dic.keys()
if DBG: print dic_keys

list_of_row_indices = [key[0] for key in dic_keys ]
if DBG: print list_of_row_indices
list_of_col_indices = [key[1] for key in dic_keys ]
if DBG: print list_of_col_indices

# print dictionary data as matrix
rows = max(list_of_row_indices)
cols = max(list_of_col_indices)
print "Matrix (%d x %d):" % (rows, cols)
for i in range(1, rows+1):
  for j in range(1, cols+1):
    # check if element is in dictionary
    if (i, j) in dic_keys:
      value = dic[i, j]
    else:
      value = 0
    # print the matrix value  
    print "%5.2f" % value,
  # \n
  print 

which gives me the output:

CODE

Matrix (3 x 4):
 2.10  0.00  0.00  0.10
 0.00  0.00  0.00  0.00
 0.00  0.40  0.00  0.00 

If you set in the script above

CODE

DBG = True 
then you will better see how the code works

CODE

C:\Work>python dic2tab.py
['1', '1', '2.1']
['1', '4', '0.1']
['3', '2', '0.4']
dictionary:
{(3, 2): 0.4, (1, 1): 2.1, (1, 4): 0.1}
list of dictionary keys:
[(3, 2), (1, 1), (1, 4)]
[3, 1, 1]
[2, 1, 4]
Matrix (3 x 4):
 2.10  0.00  0.00  0.10
 0.00  0.00  0.00  0.00
 0.00  0.40  0.00  0.00 

RE: Dictionary into a table format - Python

(OP)
Hi mikron,

I am getting this:

"matrix (3 x 4)
2.10
0.00
0.00
0.10


0.00
0.00
0.00
0.00


0.00
0.40
0.00
0.00
"

Here is your code adapted to the version 3.3:

CODE -->

def main():
        DBG=False
        sep=","
        dic={}
        for line in open('matrix.txt'):
                if line.strip():
                        line=line.strip()
                        lst=line.split(sep)
                        x=int(lst[0])
                        y=int(lst[1])
                        z=float(lst[2])
                        dic[x,y]=z
        dic_keys=dic.keys()
        list_of_row_indices=[key[0] for key in dic_keys]
        list_of_col_indices=[key[1] for key in dic_keys]
        list_of_col_indices

        rows=max(list_of_row_indices)
        cols=max(list_of_col_indices)
        print("matrix (%d x %d)" %(rows,cols))
        for i in range(1, rows+1):
                for j in range(1, cols+1):
                        if (i, j) in dic_keys:
                                value = dic[i, j]
                        else:
                                value=0
                        print("%5.2f" %value,)
                print('')

if __name__ == '__main__':
        main() 

I think there is a problem with the last print.

RE: Dictionary into a table format - Python

the instead of

CODE

print("%5.2f" %value,) 
try this

CODE

print("%5.2f" %value, end=" ") 

RE: Dictionary into a table format - Python

(OP)
Thank you so much, you have found "the cat"!

I have another question: since I am not very familiar with python, what I normally do when I have a python script it consists into send the output to a file (in linux), like this:

CODE -->

>> ./script.py > output.txt 

or

CODE -->

>>python script.py > output.txt 



I would like to substitute your print by file.write(...)

For example, using

CODE -->

file=open('output.txt','w') 

and then inside the for loop,

CODE -->

file.write("%5.2f" %value, end=" ") 

The main problem is that this last command is not working due to "wrong syntax".
Could you tell how to put your script printing the matrix for a file?
Thank you for your assistance!

RE: Dictionary into a table format - Python

Then first create the whole line you want to write into file, like

CODE

for i in range(1, rows+1):
  row_lst = []
  for j in range(1, cols+1):
    # check if element is in dictionary
    if (i, j) in dic_keys:
      value = dic[i, j]
    else:
      value = 0
    # add value to row vector 
    row_lst.append( "%5.2f" % value)
  # print the matrix line
  if DBG: print row_lst
  matrix_line = sep.join(row_lst)
  print matrix_line 
and then write this matrix_line to your output file

RE: Dictionary into a table format - Python

(OP)
Thank you for your suggestion!
However, I am getting a problem with the space, the attribute end=" " is no longer available for append
I have the following error message:

TypeError: append() takes no keyword arguments

RE: Dictionary into a table format - Python

end=" " kas usage only in print(), you don't need it in append().
Coyp the last code I posted. It must work in both Python versions.

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close