-4

I have a predefined dictionary, and I want to be able to search the keys and values of the dictionary for a target string.

For example, if this is my dictionary:

my_dict = {u'GroupName': 'yeahyeahyeah', u'GroupId': 'sg-123456'}

I want to be check whether 'yeahyeahyeah' or 'GroupId' are in the keys or values of the dictionary. I think I want to convert the entire dictionary into a string, so that I can just do a substring search, but am open to other ideas.

Jordan Singer
  • 567
  • 5
  • 11

1 Answers1

-3

EDIT: taking advice from comments

Here's how to create a list from the key value pairs in your dictionary.

my_dict = [{u'GroupName': 'yeahyeahyeah', u'GroupId': 'sg-123456'}]

my_list = list(my_dict[0].keys()) + list(my_dict[0].values())

This returns:

['GroupName', 'yeahyeahyeah', 'GroupId', 'sg-123456']
Leo Brueggeman
  • 2,241
  • 1
  • 9
  • 5
  • Disregarding that OP's question was unclear to begin with, this also is quite a roundabout way to achieve what you want... supposing you are using Python 2, `my_dict.keys() + my_dict.values()` would suffice. – r.ook Mar 29 '19 at 18:46
  • 1
    Why are you importing `itertools`? You aren't using anything it provides. – chepner Mar 29 '19 at 18:48
  • There's especially no reason to import *everything* from `itertools`. I'm really not sure why one would need to even build a list to accomplish this goal either - why not just do the check for the element in question in your for loop, instead of building out a list of keys and values? – Jordan Singer Mar 29 '19 at 18:51
  • All good points, I'm a beginner but thought I was hopefully slightly less of a beginner than OP. My response shows that is maybe not true :]. I updated the code with your input. Thank you! Might switch to consistent encoding w/ utf-8 next. – Leo Brueggeman Mar 29 '19 at 18:53
  • 2
    Your initial coding issues aside, you should also think about what the OP is looking for instead of haphazardly throwing in an answer (despite your best intentions). It is often better to ask for clarifications as your answer might not even be what OP needs. Don't take this as a discouragement, keep learning coding, but also learn beyond that if you want to be helpful. – r.ook Mar 29 '19 at 19:01
  • It should be noted that this solution *only* works in Python 2, which is generally not desirable. – Jordan Singer Mar 29 '19 at 19:09
  • Good point, edited to fix this – Leo Brueggeman Mar 29 '19 at 19:16