0

I am adding to a dictionary by doing .append within python

theDict = defaultdict(list)
theDict[theKey].append(theValue)

I'll try to print it out via

print theDict[valueKeyToLookUp]

But it always ends up looking like this:

[u'STRING_I_WANT']

I've tried doing print with str() at the front, but it still leaves the u' there.

I tried this: Python string prints as [u'String'] by doing

valueKeyToLookUp.encode('ascii')

But it still comes out the same. Other solutions look like they are looking up values via the position it is in the list by number, but I need to do it by value.

Any ideas?

Community
  • 1
  • 1
king
  • 1,304
  • 3
  • 23
  • 43
  • The following question might be of help http://stackoverflow.com/questions/19527279/python-unicode-to-ascii-conversion – JCOC611 Mar 23 '16 at 15:35

1 Answers1

2

Your dictionary doesn't contain strings, it contains lists of strings. When you print a list, that's the way Python formats it.

If you know that the list only contains a single string, just print that:

print theDict[valueKeyToLookUp][0]

If the dictionary isn't supposed to contain lists, you need to fix that.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • @king it's the index of the first string in the list. Your question doesn't really go into which string you want to print. – Mark Ransom Mar 23 '16 at 15:37
  • the one that matches the key i put into there – king Mar 23 '16 at 15:38
  • oh you mean each entry into the dictionary is a list? and you can grab a specific one? each part of the dictionary is actually just one value – king Mar 23 '16 at 15:39
  • so maybe i dont really need a list to be there – king Mar 23 '16 at 15:39
  • @king so you have a dictionary whose keys and contents are identical? That doesn't make any sense whatsoever. Maybe you should be using a [`set`](https://docs.python.org/2/library/stdtypes.html#set) – Mark Ransom Mar 23 '16 at 15:40
  • no.. i have a key like "theDogName". and a value like, "Buddy". So I want to get Buddy, so I do, print theDict['theDogName'] – king Mar 23 '16 at 15:41
  • 2
    @king, build the dict with `theDict['theDogName'] = 'Buddy'` instead of making default values empty lists that you are appending to. – Mark Tolonen Mar 23 '16 at 15:55
  • you mean just start it like that without even declaring it with a list? cool – king Mar 23 '16 at 16:13