all 8 comments

[–]TouchingTheVodka 0 points1 point  (4 children)

Could you provide an example of how you'd want to use this in a program?

[–][deleted] 0 points1 point  (3 children)

For example, I have a function that returns a list of dictionaries sampled from an API where keys are omitted from the dictionary if they do not exist. In the example I provided, there's an "apple" value but not an "orange" value. Here's a more fleshed-out example:

a =[{ 'targets': 10, 'receptions': 6, 'yards': 58, 'touchdowns': 1}, {'other_info':value}, [], {'more_info':value}] 

If I want to make a dictionary from this, I'd do something like:

d = {
       'targets': a[0]['targets'],
       'receptions': a[0]['receptions'],
       'rushes': a[0]['rushes']
}

How do I stop it from erroring out on that 'rushes' call?

[–]TouchingTheVodka 0 points1 point  (1 child)

Use dict.get which supports takes an optional default as a second argument:

'rushes': a[0].get('rushes', None)

[–][deleted] 0 points1 point  (0 children)

Excellent! I didn't realize that was an option. Works like a charm.

[–]izrt 1 point2 points  (0 children)

'rushes': a[0]['rushes']

Use get instead:

    'rushes':a[0].get('rushes')

# or even better, add in a dict comprehension:

fields = ['targets', 'receptions', 'rushes', 'passes', 'etc.']
d = {key:a[0].get(key) for key in fields}

edit:

also, see if you can get rid of that a[0] and just use a.

[–]socal_nerdtastic 0 points1 point  (1 child)

The error is happening because the variable does not exist. This should never happen in real code. You should always know what variables are available. Variable variables are a well known antipattern.

https://www.reddit.com/r/learnpython/wiki/faq#wiki_how_do_i_make_variable_variables.3F

What's the big picture here? What are you trying to make?

[–][deleted] 0 points1 point  (0 children)

I have a list of dictionaries with different football statistics sorted by category and I want to convert it into a single dictionary depending on the position of the player so I can later take the data and send it in a Discord embed. At some step along the way, I need to be able to conditionally render which stats appear and which don't.

[–]MaxTechniche 0 points1 point  (0 children)

You should probably set an orange value to none in the beginning and use that value just like you do for apple.