Zyberg
Zyberg

Reputation: 187

How to create a dictionary with key being value of a variable in python?

I mean to somehow translate this pseudo code into python3 code: dict(itemName = itemRecipe)

What I have tried so far:

1)

allItems = [{}]
itemName = 'Pancake'
itemRecipe = ['Eggs', 'Flour']
allItems[0].update(dict(itemName = itemRecipe))

That yields me an array and with an object that has key called 'itemName', not 'Pancake'.

2)

allItems = [{}]
itemName = 'Pancake'
itemRecipe = ['Eggs', 'Flour']
allItems[0].update(dict(locals()[itemName] = itemRecipe))

Throws me a SyntaxError: keyword can't be an expression.

I am at a loss of what to do. Maybe anybody could help me there?

Upvotes: 0

Views: 87

Answers (4)

JohnAD
JohnAD

Reputation: 899

If you are doing a lot of list-of-dictionary manipulation, you can use the PLOD library:

from PLOD import PLOD

allItems = [{}]
itemName = 'Pancake'
itemRecipe = ['Eggs', 'Flour']

new_list = PLOD(allItems).\
    missingKey("itemName").\
    addKey("itemName", itemName).\
    addKey("itemRecipe", itemRecipe).\
    returnList()

This code locates all dictionary entries that do not have the "itemName" key. It then applies "itemName" and "itemRecipe" to that list of dictionaries.

The result:

>>> new_list
[{'itemRecipe': ['Eggs', 'Flour'], 'itemName': 'Pancake'}]

Or, to get fancy:

>>> print (PLOD(new_list).returnString())
[
    {itemName: 'Pancake', itemRecipe: ['Eggs', 'Flour']}
]

I only recommend this library if your code is filled with such manipulations. It is a lot of overhead if just doing this once.

This library can be found at PyPI and GitHub for python 2.7.x.

Upvotes: 0

joshua
joshua

Reputation: 28

allItems = [{}]
itemName = 'Pancake'
itemRecipe = ['Eggs', 'Flour']
allItems[0][itemName] = itemRecipe
print(allItems)

Upvotes: 0

fuglede
fuglede

Reputation: 18221

There is no attribute on list called update, but it is not clear what you are trying to achieve with that, but if what you want is a single-element list containing a dictionary whose key is itemName, and whose corresponding value is itemRecipe, you could simply let allItems = [{itemName: itemRecipe}].

Upvotes: 1

vZ10
vZ10

Reputation: 2686

 allItems.update({itemName: itemRecipe})

but in your code allItems (btw camelcase is not in honor in Python) is a List so you should append it

 allItems.append({itemName: itemRecipe})

And if you want allItems to be a dict you can just do like

 allItems = {}
 allItems[itemName] = itemRecipe

Upvotes: 5

Related Questions