Python dictionary simple way to add a new key value pair
Say you have,
foo = 'bar'
d = {'a-key':'a-value'}
And you want
d = {'a-key':'a-value','foo':'bar'}
e = {'foo':foo}
I know you can do,
d['foo'] = foo
#Either of the following for e
e = {'foo':foo}
e = dict(foo=foo)
But, in all these way to add the variable foo to dict, I have had to use the word foo
twice; once to indicate the key and once for its value.
It seems wasteful to me to use foo
twice. Is there a simpler way, in which you can tell python "Add this variable to the dictionary with its name as the key and its value as the value"?
Asked by: Kirsten445 | Posted: 30-11-2021
Answer 1
you can do something like this
def add_dry_foo(d, namespace, fooName):
d[fooName] = namespace[fooName]
foo = 'oh-foo'
d = {}
add_dry_foo(d, locals(), 'foo')
print d
Answered by: Abigail727 | Posted: 01-01-2022
Answer 2
Actutally using foo
twice is remarkably common in python programs. It is used extensively for passing on arguments eg
def f(foo, bar):
g(foo=foo)
Which is a specialised case of the dictionary manipulations in your question.
I don't think there is a way of avoiding it without resorting to magic, so I think you'll have to live with it.
Answered by: Brad684 | Posted: 01-01-2022Answer 3
You can use:
name = 'foo'
d[name] = vars[name]
I don't see the difference between your d
and e
cases: both set 'foo' to the value of foo.
It gets trickier if you want to bury this in a function:
def add_variable(d, name):
# blah
because then it has to use inspect
to start poking around in frames.
This sounds like a larger problem that might have a nicer solution if you wanted to describe it to us. For example, if the problem is that you don't care just about foo, but in fact, a whole slew of local variables, then maybe you want something like:
d.update(locals())
which will copy the names and value of all the local variables into d
.
Answer 4
If you don't want to pass all of locals()
(which may be a security risk if you don't fully trust the function you're sending the data too), a one-line answer could be this:
dict([ (var, locals()[var]) for var in ['foo', 'bar'] ])
or in Python 3.0 this would become possible:
{ var: locals()[var] for var in ['foo', 'bar'] }
Answer 5
To add all the local variables to a dict you can do:
d.update(locals())
The same works for function calls:
func(**locals())
Note that depending on where you are locals()
might of course contain stuff that should not end up in the dict. So you could implement a filter function:
def filtered_update(d, namespace):
for key, value in namespace.items():
if not key.startswith('__'):
d[key] = value
filtered_update(d, locals())
Of course the Python philosophy is "explicit is better than implicit", so generally I would walk the extra mile and do this kind of stuff by hand (otherwise you have to be careful about what goes on in your local namespace).
Answered by: Adelaide990 | Posted: 01-01-2022Answer 6
You could use eval, although I'm not sure that I'd recommend it.
>>> d = dict()
>>> foo = 'wibble'
>>> def add(d, name):
d[name] = eval(name)
>>> add(d, 'foo')
>>> d
{'foo': 'wibble'}
Edit: I should point out why I don't recommend "eval". What happens if you do something like this? (from: http://mail.python.org/pipermail/tutor/2005-November/042854.html)
>>> s = "(lambda loop: loop(loop)) (lambda self: self(self))"
>>> add(d, s)
Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
add(d, s)
File "<pyshell#43>", line 2, in add
d[name] = eval(name)
File "<string>", line 1, in <module>
File "<string>", line 1, in <lambda>
File "<string>", line 1, in <lambda>
...
File "<string>", line 1, in <lambda>
RuntimeError: maximum recursion depth exceeded
Answered by: Fiona284 | Posted: 01-01-2022
Answer 7
It seems to me what you are talking about is an enhancement to parameter passing functionality:
def func(*vars):
provides a tuple of ordered values without keys
def func(**vars):
provides a dict of key value pairs, that MUST be passed as key=value pairs.
def func(***vars):
WOULD PROVIDE a dict of key value pairs, passed either explicitly as key=value, or implicitly as key (a variable, literals would cause error without key=)
SO:
(x1,x2,x3) = (1,2,3)
def myfunc(***vars):
retrun vars
myfunc(x1,x2,x3)
>>> {'x1':1,'x2':2,'x3':3}
But of course, this is just wishful thinking...
Answered by: Steven429 | Posted: 01-01-2022Similar questions
python - Simple file to dictionary
So I have the file below with the following values. What I am trying to do is to put these int values into a dictionary.
0 0
0 1
0 2
0 3
0 4
1 1
1 2
1 3
1 4
1 5
2 3
2 4
3 3
4 5
5 0
I want my dictionary to look something along the lines of...
graph = {0: [0,1,2,3,4],1: [1,2,3,4,5], 2: [3,4] .... and so on.
I am currently using code from the following quest...
python - simple dictionary for getting value
names = ['a', 'b', 'c']
values = range(1,4)
dicts = dict(zip(names, values))
this_name = 'b'
How to get the value 2 here?
python - Simple Dictionary
The question asks to write a function creating a dictionary with the count of each word in the string and only remove the punctuation if it is the last character in the word. I've been trying to solve the punctuation part of the problem. For the assignment I need to identify the punctuation using isalpha, but
I'm not sure if using the word[-1] is helping to identify if the last char...
python - List all words in a dictionary that start with <user input>
How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?
Ex:
User: "abd"
Program:abdicate, abdomen, abduct...
Thanks!
Edit: I'm using python, but I assume that this is a fairly language-independent problem.
python, dictionary and int error
I have a very frustrating python problem. In this code
fixedKeyStringInAVar = "SomeKey"
def myFunc(a, b):
global sleepTime
global fixedKeyStringInAVar
varMe=int("15")
sleepTime[fixedKeyStringInAVar] = varMe*60*1000
#more code
Now this works. BUT sometimes when I run this function I get
TypeError: 'int' object does not support item assignment
python - Best way to create a NumPy array from a dictionary?
I'm just starting with NumPy so I may be missing some core concepts...
What's the best way to create a NumPy array from a dictionary whose values are lists?
Something like this:
d = { 1: [10,20,30] , 2: [50,60], 3: [100,200,300,400,500] }
Should turn into something like:
data = [
[10,20,30,?,?],
[50,60,?,?,?],
[100,200,300,400,500]
]
...
python - List a dictionary
In a list appending is possible. But how I achieve appending in dictionary?
Symbols from __ctype_tab.o:
Name Value Class Type Size Line Section
__ctype |00000000| D | OBJECT|00000004| |.data
__ctype_tab |00000000| r | OBJECT|00000101| |.rodata
Symbols from _ashldi3.o:
Name Value Class ...
python - How to filter a dictionary by value?
Newbie question here, so please bear with me.
Let's say I have a dictionary looking like this:
a = {"2323232838": ("first/dir", "hello.txt"),
"2323221383": ("second/dir", "foo.txt"),
"3434221": ("first/dir", "hello.txt"),
"32232334": ("first/dir", "hello.txt"),
"324234324": ("third/dir", "dog.txt")}
I want all values that are equal to each other to be moved into...
Python and dictionary like object
I need a python 3.1 deep update function for dictionaries (a function that will recursively update child dictionaries that are inside a parent dictionary).
But I think, in the future, my function could have to deal with objects that behave like dictionaries but aren't. And furthermore I want to avoid using isinstance and type (because they are considered b...
python - Remove dictionary from list
If I have a list of dictionaries, say:
[{'id': 1, 'name': 'paul'},
{'id': 2, 'name': 'john'}]
and I would like to remove the dictionary with id of 2 (or name 'john'), what is the most efficient way to go about this programmatically (that is to say, I don't know the index of the entry in the list so it can't simply be popped).
C# way to mimic Python Dictionary Syntax
Is there a good way in C# to mimic the following python syntax:
mydict = {}
mydict["bc"] = {}
mydict["bc"]["de"] = "123"; # <-- This line
mydict["te"] = "5"; # <-- While also allowing this line
In other words, I'd like something with [] style access that can return either another dictionary or a string type, depending on how it has been set.
I've been trying to work...
python - Can a dictionary be passed to django models on create?
Is it possible to do something similar to this with a list, dictionary or something else?
data_dict = {
'title' : 'awesome title',
'body' : 'great body of text',
}
Model.objects.create(data_dict)
Even better if I can extend it:
Model.objects.create(data_dict, extra='hello', extra2='world')
python - Make Dictionary From 2 List
This question already has answers here:
sorting - In Python, how can you easily retrieve sorted items from a dictionary?
Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added.
What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?
For example, you had this:
d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
Python dictionary from an object's fields
Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:
>>> class Foo:
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }
NOTE: It should not include methods. Only fields.
python - How do you retrieve items from a dictionary in the order that they're inserted?
Is it possible to retrieve items from a Python dictionary in the order that they were inserted?
python - How can I make a dictionary from separate lists of keys and values?
I want to combine these:
keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
Into a single dictionary:
{'name': 'Monty', 'age': 42, 'food': 'spam'}
python - Dictionary or If statements, Jython
I am writing a script at the moment that will grab certain information from HTML using dom4j.
Since Python/Jython does not have a native switch statement I decided to use a whole bunch of if statements that call the appropriate method, like below:
if type == 'extractTitle':
extractTitle(dom)
if type == 'extractMetaTags':
extractMetaTags(dom)
Is a Python dictionary an example of a hash table?
One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?
python - Is there a "one-liner" way to get a list of keys from a dictionary in sorted order?
The list sort() method is a modifier function that returns None.
So if I want to iterate through all of the keys in a dictionary I cannot do:
for k in somedictionary.keys().sort():
dosomething()
Instead, I must:
keys = somedictionary.keys()
keys.sort()
for k in keys:
dosomething()
Is there a pretty way to iterate t...
python - Interface to versioned dictionary
I have an versioned document store which I want to access through an dict like interface.
Common usage is to access the latest revision (get, set, del), but one should be able to access specific revisions too (keys are always str/unicode or int).
from UserDict import DictMixin
class VDict(DictMixin):
def __getitem__(self, key):
if isinstance(key, tuple):
docid, rev = key
e...
python - List all words in a dictionary that start with <user input>
How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?
Ex:
User: "abd"
Program:abdicate, abdomen, abduct...
Thanks!
Edit: I'm using python, but I assume that this is a fairly language-independent problem.
python - Check if a given key already exists in a dictionary and increment it
How do I find out if a key in a dictionary has already been set to a non-None value?
I want to increment the value if there's already one there, or set it to 1 otherwise:
my_dict = {}
if my_dict[key] is not None:
my_dict[key] = 1
else:
my_dict[key] += 1
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python