1

I have written a small test script:

#!/usr/bin/env python

import pexpect
import re


List_dictionary = {
'b -c \\"select name,type,is_supported from algorithm where name = \\\'RSA\\\' and key_size=1024 \\"':'app \"algo -e -n RSA -ks 1024\"',

'b -c \\"select name,type,is_supported from algorithm where name = \\\'RSA\\\' and key_size=1024 \\"':'app \"algo -d -n RSA -ks 1024\"'
}

test_dict={
'a':1,
'b':2
}

for a,b in List_dictionary.items():
        print a
for a,b in test_dict.items():
        print a
print len(List_dictionary)
print len(test_dict)

The output I am getting is:

./test.py
b -c \"select name,type,is_supported from algorithm where name = \'RSA\' and key_size=1024 \"
a
b
1
2

Why is only one element fetched from List_dictionary and the length of it is 1. Instead as per my knowledge it should be 2.

user1939168
  • 547
  • 5
  • 20
  • 1
    Because the first is not a dictionary. You need a `key : value` pair. And since both keys in this example are identical, the second one replaces the first key (with no value). – Torxed Jul 14 '15 at 13:25
  • @Torxed: It has a key value pair otherwise `List_dictionary.items()` would give an AttributeError. – GWW Jul 14 '15 at 13:26
  • @GWW my bad, didn't notice the `':'` because it was so tight and the syntax highlight didn't do a good job of pointing it out. – Torxed Jul 14 '15 at 13:28
  • Have you tried looking to see what's actually *in* `List_dictionary`? How was that not the first thing you checked?! – jonrsharpe Jul 14 '15 at 13:30

1 Answers1

4

It's quite easy.

Dictionaries work in such a way that every key is unique in the key : value pair. Meaning your second key in your dictionary replaces the first because they are identical.

'b -c \\"... \\"'
'b -c \\"... \\"'

Try changing one letter to say, ´c -c` at the start to try it out.
Another solution would be to set a proper key for your command/string and (as GWW mentioned below) put both your commands in a list instead. consider the following:

List_dictionary = {
    'first' : ['b -c \\"select name,type,is_supported from algorithm where name = \\\'RSA\\\' and key_size=1024 \\"', 'app \"algo -e -n RSA -ks 1024\"'],
    'sendond' : ['b -c \\"select name,type,is_supported from algorithm where name = \\\'RSA\\\' and key_size=1024 \\"', 'app \"algo -d -n RSA -ks 1024\"']
}

This gives you unique keys and makes the whole dictionary a bit cleaner.
You could even rename the keys from first/second/ to algo -e and algo -d since spaces are allowed in the keys field.

Torxed
  • 22,866
  • 14
  • 82
  • 131
  • 2
    It may be worthwhile to mention that a list could be used as the value to associate more than one value with a key. There are a couple examples [here](http://stackoverflow.com/questions/5378231/python-list-to-dictionary-multiple-values-per-key) – GWW Jul 14 '15 at 13:30