2

I have two numpy.ndarray

[[' THE OLD TESTAMENT ']
[' SEAN SONG ']
[' CITY WALK ']]

and

[[' This is the name of an Old Testament ']
 [' Hello this is great ']
[' Wait the way you are doing ']]

I want to convert these ndarray to dictionary.

 {
"THE OLD TESTAMENT": "This is the name of an Old Testament",
"SEAN SONG": "Hello this is great",
"CITY WALK": Wait the way you are doing 
 }

I am using the code written below

keys = df.as_matrix()
print (keys)
values = df1.as_matrix()
print (values)
new_dict = dict(izip(keys, values))
1
  • 2
    The real question is how did you end up with these horrible arrays? Commented Nov 29, 2018 at 7:29

4 Answers 4

2

Converting to arrays is not necessary, use iloc for select first column with zip:

new_dict = dict(zip(df.iloc[:, 0], df1.iloc[:, 0]))

Or select columns by names:

new_dict = dict(zip(df['col'], df1['col']))
Sign up to request clarification or add additional context in comments.

Comments

1

Squeeze your arrays first:

In [1]: import numpy as np

In [2]: keys = np.array(
   ...:     [[' THE OLD TESTAMENT '],
   ...:     [' SEAN SONG '],
   ...:     [' CITY WALK ']]
   ...: )

In [3]: values = np.array(
   ...:     [[' This is the name of an Old Testament '],
   ...:      [' Hello this is great '],
   ...:     [' Wait the way you are doing ']]
   ...: )

In [4]: dict(zip(keys.squeeze(), values.squeeze()))
Out[4]:
{' CITY WALK ': ' Wait the way you are doing ',
 ' SEAN SONG ': ' Hello this is great ',
 ' THE OLD TESTAMENT ': ' This is the name of an Old Testament '}

Or just use slicing:

In [5]: dict(zip(keys[:,0], values[:,0]))
Out[5]:
{' CITY WALK ': ' Wait the way you are doing ',
 ' SEAN SONG ': ' Hello this is great ',
 ' THE OLD TESTAMENT ': ' This is the name of an Old Testament '}

Comments

0
keyh=[[' THE OLD TESTAMENT '],
[' SEAN SONG '],
[' CITY WALK ']]

valueh=[[' This is the name of an Old Testament '],
 [' Hello this is great '],
[' Wait the way you are doing ']]

dictionary = dict(zip([item[0] for item in keyh], [item[0] for item in valueh]))

Output

{
"THE OLD TESTAMENT": "This is the name of an Old Testament",
"SEAN SONG": "Hello this is great",
"CITY WALK": "Wait the way you are doing"
 }

Comments

0
keys = [[' THE OLD TESTAMENT '],[' SEAN SONG '],[' CITY WALK ']]

values = [[' This is the name of an Old Testament '], [' Hello this is great '],[' Wait the way you are doing ']]


keys = [x[0] for x in keys]

values = [x[0] for x in values]


dictionary = dict(zip(keys, values))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.