Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dictionary into a table format - Python 1

Status
Not open for further replies.

nvhuser

Programmer
Apr 10, 2015
48
DE
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!

 
You can try something like this:
Code:
dic = {([COLOR=#ff00ff]1[/color],[COLOR=#ff00ff]1[/color]):[COLOR=#ff00ff]'a'[/color], ([COLOR=#ff00ff]1[/color],[COLOR=#ff00ff]2[/color]):[COLOR=#ff00ff]'b'[/color], ([COLOR=#ff00ff]1[/color],[COLOR=#ff00ff]3[/color]):[COLOR=#ff00ff]'c'[/color],
       ([COLOR=#ff00ff]2[/color],[COLOR=#ff00ff]1[/color]):[COLOR=#ff00ff]'t'[/color], ([COLOR=#ff00ff]2[/color],[COLOR=#ff00ff]2[/color]):[COLOR=#ff00ff]'u'[/color], ([COLOR=#ff00ff]2[/color],[COLOR=#ff00ff]3[/color]):[COLOR=#ff00ff]'v'[/color]}

[COLOR=#008080]print[/color] [COLOR=#ff00ff]"dictionary:"[/color]
[COLOR=#008080]print[/color] dic

[COLOR=#008080]print[/color] [COLOR=#ff00ff]"matrix:"[/color]
rows = [COLOR=#ff00ff]2[/color]
col = [COLOR=#ff00ff]3[/color]
[COLOR=#804040][b]for[/b][/color] i [COLOR=#804040][b]in[/b][/color] [COLOR=#008080]range[/color]([COLOR=#ff00ff]1[/color], rows+[COLOR=#ff00ff]1[/color]):
  [COLOR=#804040][b]for[/b][/color] j [COLOR=#804040][b]in[/b][/color] [COLOR=#008080]range[/color]([COLOR=#ff00ff]1[/color], col+[COLOR=#ff00ff]1[/color]):
    [COLOR=#0000ff]# print line[/color]
    [COLOR=#008080]print[/color] dic[(i, j)],
  [COLOR=#0000ff]# \n[/color]
  [COLOR=#008080]print[/color]

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
 
to access the dictionary value you can use dic[i, j] (instead of dic[(i, j)])
 
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!
 
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 = {([COLOR=#ff00ff]1[/color],[COLOR=#ff00ff]1[/color]):[COLOR=#ff00ff]'a'[/color], ([COLOR=#ff00ff]1[/color],[COLOR=#ff00ff]2[/color]):[COLOR=#ff00ff]'b'[/color], ([COLOR=#ff00ff]1[/color],[COLOR=#ff00ff]3[/color]):[COLOR=#ff00ff]'c'[/color],
       ([COLOR=#ff00ff]2[/color],[COLOR=#ff00ff]1[/color]):[COLOR=#ff00ff]'t'[/color], ([COLOR=#ff00ff]2[/color],[COLOR=#ff00ff]2[/color]):[COLOR=#ff00ff]'u'[/color], ([COLOR=#ff00ff]2[/color],[COLOR=#ff00ff]3[/color]):[COLOR=#ff00ff]'v'[/color]}

[COLOR=#008080]print[/color] [COLOR=#ff00ff]"dictionary:"[/color]
[COLOR=#008080]print[/color] dic

[COLOR=#008080]print[/color] [COLOR=#ff00ff]"list of dictionary keys:"[/color]
dic_keys = dic.keys()
[COLOR=#008080]print[/color] dic_keys

list_of_row_indices = [key[[COLOR=#ff00ff]0[/color]] [COLOR=#804040][b]for[/b][/color] key [COLOR=#804040][b]in[/b][/color] dic_keys ]
[COLOR=#008080]print[/color] list_of_row_indices
list_of_col_indices = [key[[COLOR=#ff00ff]1[/color]] [COLOR=#804040][b]for[/b][/color] key [COLOR=#804040][b]in[/b][/color] dic_keys ]
[COLOR=#008080]print[/color] list_of_col_indices

rows = [COLOR=#008080]max[/color](list_of_row_indices)
cols = [COLOR=#008080]max[/color](list_of_col_indices)
[COLOR=#008080]print[/color] [COLOR=#ff00ff]"matrix (%d x %d):"[/color] % (rows, cols)
[COLOR=#804040][b]for[/b][/color] i [COLOR=#804040][b]in[/b][/color] [COLOR=#008080]range[/color]([COLOR=#ff00ff]1[/color], rows+[COLOR=#ff00ff]1[/color]):
  [COLOR=#804040][b]for[/b][/color] j [COLOR=#804040][b]in[/b][/color] [COLOR=#008080]range[/color]([COLOR=#ff00ff]1[/color], cols+[COLOR=#ff00ff]1[/color]):
    [COLOR=#0000ff]# print line[/color]
    [COLOR=#0000ff]#print dic[(i, j)],[/color]
    [COLOR=#008080]print[/color] dic[i, j],
  [COLOR=#0000ff]# \n[/color]
  [COLOR=#008080]print[/color]
 
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
 
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]+",")
 
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
 
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:

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()
 
Sorry but I need to use python 3.3, it is sadly mandatory =(
 
nvhuser said:
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, [highlight]rows+1[/highlight]):
... 	print i
... 
1
2
3
4
5
 
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!
 
 http://files.engineering.com/getfile.aspx?folder=16307d1b-1d99-4a54-be31-9a55ee65866f&file=out_matrix2.txt
nvhuser said:
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:
[COLOR=#0000ff]# set DebugInfo True or False[/color]
DBG = [COLOR=#008080]False[/color]
[COLOR=#0000ff]# read data from a file into dictionary[/color]
sep = [COLOR=#ff00ff]","[/color]
dic ={}
[COLOR=#804040][b]for[/b][/color] line [COLOR=#804040][b]in[/b][/color] [COLOR=#008080]open[/color]([COLOR=#ff00ff]'matrix.txt'[/color]):
  [COLOR=#0000ff]# when line not empty[/color]
  [COLOR=#804040][b]if[/b][/color] line.strip():
    [COLOR=#0000ff]# remove \n[/color]
    line = line.strip()
    [COLOR=#0000ff]# split line into list[/color]
    lst = line.split(sep)
    [COLOR=#804040][b]if[/b][/color] DBG: [COLOR=#008080]print[/color] lst
    [COLOR=#0000ff]# populate dictionary[/color]
    x = [COLOR=#008080]int[/color](lst[[COLOR=#ff00ff]0[/color]])
    y = [COLOR=#008080]int[/color](lst[[COLOR=#ff00ff]1[/color]])
    z = [COLOR=#008080]float[/color](lst[[COLOR=#ff00ff]2[/color]])
    dic[x, y] = z

[COLOR=#0000ff]# print dictionary[/color]
[COLOR=#804040][b]if[/b][/color] DBG: 
  [COLOR=#008080]print[/color] [COLOR=#ff00ff]"dictionary:"[/color]
  [COLOR=#008080]print[/color] dic

[COLOR=#804040][b]if[/b][/color] DBG: [COLOR=#008080]print[/color] [COLOR=#ff00ff]"list of dictionary keys:"[/color]
dic_keys = dic.keys()
[COLOR=#804040][b]if[/b][/color] DBG: [COLOR=#008080]print[/color] dic_keys

list_of_row_indices = [key[[COLOR=#ff00ff]0[/color]] [COLOR=#804040][b]for[/b][/color] key [COLOR=#804040][b]in[/b][/color] dic_keys ]
[COLOR=#804040][b]if[/b][/color] DBG: [COLOR=#008080]print[/color] list_of_row_indices
list_of_col_indices = [key[[COLOR=#ff00ff]1[/color]] [COLOR=#804040][b]for[/b][/color] key [COLOR=#804040][b]in[/b][/color] dic_keys ]
[COLOR=#804040][b]if[/b][/color] DBG: [COLOR=#008080]print[/color] list_of_col_indices

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

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 = [COLOR=#008080]True[/color]
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
 
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.
 
the instead of
Code:
print("%5.2f" %value,)
try this
Code:
print("%5.2f" %value, end=" ")
 
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!

 
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 
    [highlight]row_lst.append( "%5.2f" % value)[/highlight]
  # print the matrix line
  if DBG: print row_lst
  [highlight]matrix_line = sep.join(row_lst)[/highlight]
  print matrix_line
and then write this [highlight]matrix_line[/highlight] to your output file
 
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

 
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.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top