Assign list values to dictionary keys - python

So I want to loop over a dictionary and a list simultaneously without them being nested.
What I really mean is:
for i,c in enumerate(dictionary) and for k in range(len(list)):
dictionary[c] = list[k]
So it basically loops over one dictionary and I can assign values to the dictionary with a list.

IIUC, you are trying to reassign existing keys to list values. This is something you can only do from python-3.7 onwards (or 3.6 if you use CPython). This can be done either through direct reassignment,
dictionary = dict(zip(dictionary, lst))
Or, if they are not the same length, and there are keys you want to preserve, use dict.update:
dictionary.update(dict(zip(dictionary, lst)))
Additionally, it is unwise to name variables after builtin objects (such as list).

zip is your friend
dictionary.update(zip(dictionary, lst))

Related

Python: using a loop to do the same with several variables

I have 30 variables with the pattern aod7039, aod7040, ...., aod7068.
I want to do the same operation (i.e. calculate the mean over an axis) for all these variables and overwrite the original variables.
Up to now I wrote 30 times the same line, and wondered if there isn't maybe an shorter and easier way to do this?
I am gradeful for every idea!
Firstly, don't use 30 variables, use a list aod[]
Secondly, use
for i in range(7039, 7069):
aod[i] = yourFunction(aod[i])
to override existing list
This will get you all values of variables that start with 'aod'
values = [v for k,v in globals() if k.startswith('aod')]
But having 30 variables smells bad.
If I understand your question right, you just want to iterate over those variables?
If so you could keep references on some list/dictionary and then iterate/update this way.
List = []
List.append(aod7039)
for item in List:
#do something
I have 30 variables with the pattern aod7039, aod7040, ...., aod7068
Then you have a design problem - you should have a list or dict instead. Replace all those variables with either a list or dict (or collections.OrderedDict if you need key access while preserving insertion order) and then it's only a matter of iterating over your container, ie
# with a list:
for index, item in enumerate(yourlist):
yourlist[index] = do_something_with(item)
# with a dict or OrderedDict:
for key, item in enumerate(yourdict):
yourdic[key] = do_something_with(item)
store your 30 variables in a list and use map to tackle it without any loop:
varlist=[aod7039, aod7040, ...., aod7068]
result=list(map(yourfunction, varlist))

summing dict value of list to single integer

I am trying to do something pretty simple but cant seem to get it. I have a dictionary where the value is a list. I am trying to just sum the list and assign the value back to the same key as an int. Using the code below the first line doesn't do anything, the second as it says puts the value back but in a list. All other things ive tried has given me an error can only assign iterable. As far as i know iterables are anything that can be iterated on such as list and not int. Why can I only use iterable and how can i fix this issue ? The dict im using is here (https://gist.github.com/ishikawa-rei/53c100449605e370ef66f1c06f15b62e)
for i in dict.values():
i = sum(i)
#i[:] = [sum(i) / 3600] # puts answer into dict but as a list
You can use simple dictionary comprehension if your dict values are all lists
{k:sum(v) for k, v in dict.items()}
for i in dikt.keys():
dickt[i] = sum(dict[i]))
btw, dict is a type. best not to use it as a variable name

In Python 3.X, how do you program a print to only occur if the input.split() contains none of the items being checked in a for loop? [duplicate]

Given the following code
all_options = { "1": "/test/1", "2": "/test/2", "3": "/test/3" }
selected_options = [ "1", "3" ]
How do I get the entries from all_options where the key matches an entry in selected_options?
I started down the path of using a List Comprehension, but I'm stuck on the last clause:
final = ()
[ final.append(option) for option in all_options if ... ]
Thank you
Just like this?
>>> dict((option, all_options[option]) for option in selected_options if option in all_options)
{'1': '/test/1', '3': '/test/3'}
From Python 2.7 and 3 onwards, you can use the dict comprehension syntax:
{option : all_options[option] for option in selected_options if option in all_options}
Or if you just want the values:
>>> [all_options[option] for option in selected_options if option in all_options]
['/test/1', '/test/3']
[option for option in all_options if option in selected_options]
You may want to make a set of selected_options and use that instead if there are many.
How do I get the entries from all_options where the key matches an entry in selected_options?
With a comprehension. We have two kinds: list comprehensions and generator comprehensions.
Note that this depends on what you mean by "entries". If you want a dict with the key/value pairs that match, then you'll need a comprehension that creates the key/value pairs, and then use that to create a dict by feeding it to the dict constructor.
There is a special syntax rule that says that if we call something callable (like, say, a class constructor) with just one argument, and that argument is a generator comprehension, then we only need one pair of parentheses (instead of two: one to call the function and another to mark the comprehension as a comprehension). This lets us write very natural-looking things.
On the other hand, if you just want a list of keys, then you can just use a list comprehension. (You could pass a generator comprehension to the list constructor, too.)
I started down the path of using a List Comprehension...
You have the wrong idea, fundamentally, about how they work. You don't use them to perform an action repeatedly; you use them to calculate a result repeatedly. You wouldn't make an append call in the first part of the statement because (a) the comprehension is already building the sequence for you, so there's no reason to create another empty sequence to append to; (b) the append call returns None after doing the appending, so you end up with a list of None values that you subsequently throw away.
A list comprehension creates a value. A generator comprehension also creates a value, but it's a generator (so you have to extract its values to use them).
So, how do we write the code?
A list of keys looks like this: for each key in the dict (iterating over a dict iterates over its keys), we want that key (with no modification), only if the key is in our other list. That is, we want [key for key in all_options if key in selected_options]. And that's exactly how you write it in Python. A language could hardly read any more naturally while still being unambiguous.
A dict of key-value pairs looks like this: for each key-value pair in the key-value pairs of the dict, we want that pair, only if the key is in our other list. We want to make a dict using those key-value pairs, so we wrap the comprehension in the dict constructor. To get key-value pairs from a dict, we iterate over its .items(). So, we want a dict constructed from a key and value, for each key and value in the items of the original dict, where the key is in the other list. And again, that's exactly what we write: dict((key, value) for (key, value) in all_options if key in selected_options).
In more recent versions of Python, we can also use a "dict comprehension", which is basically syntactic sugar so that we can write something that looks more like the list comprehension.
Use set() instead, and take advantage of the intersection operation:
>>> final = set(all_options.keys()) & set(selected_options)
>>> print(final)
{'1', '3'}
The above only returns the keys, but NullUserException notes that the question may want the value as well, using a dict comprehention:
>>> {x: all_options[x] for x in set(all_options.keys()) & set(selected_options)}
{'1': '/test/1', '3': '/test/3'}
For completeness, here's just the value:
>>> [all_options[x] for x in set(all_options.keys()) & set(select_options)]
['/test/1', '/test/3']
The below is wrong. Using set() iterates over both lists, instead of just one.
Using sets is better assuming the options become large. The conditional list comprehensions check every item in one of the containers, but a set intersection takes advantage of Python's excellent hashing. Even the list comprehension here only looks up the desired keys in all_options.
I'm not sure which exact contents you're trying to return, so I'm giving a couple of choices:
if your trying to return: ['1', '3']
[option for option in all_options if option in selected_options]
OR
if you're trying to return: ['/test/1', '/test/3']
[all_options[option] for option in all_options if option in selected_options]

Access array based on number of named key

json_data = {"fruits": ["apple", "banana", "orange"],"vegetables":["tomatoe", "cucumber", "potato"]}
How do I access my array numerically without having to include a numeric key?
ex:
json_data[0][0] #result should equal "apple"
You can't. The outer container is an unordered dictionary, not a list, so an index of 0 is meaningless. If you have some way of ordering the keys, you could then use the dict.keys() function to build a list and index that. The problem is, that keys() can come up in any order, so you'd still need some other ordering principle.
json_data[list(json_data.keys())[0]][0]
this is how to do it, but it is extremely wrong, ugly and unpythonic, and you should probably be looking for another way to do this.
starting from the inside json_data.keys() returns all the keys
list() turns those keys into a list [0] after it, accesses the zeroth item in the list
json_data[] around that accesses the list by key
[0] after it accesses the zeroth item in the returned list
Also it is not guaranteed to work 100% of the time, because json_data.keys() is not guaranteed to always output at the same order.

Python: Check if any list element is a key in a dictionary

Given the following code
all_options = { "1": "/test/1", "2": "/test/2", "3": "/test/3" }
selected_options = [ "1", "3" ]
How do I get the entries from all_options where the key matches an entry in selected_options?
I started down the path of using a List Comprehension, but I'm stuck on the last clause:
final = ()
[ final.append(option) for option in all_options if ... ]
Thank you
Just like this?
>>> dict((option, all_options[option]) for option in selected_options if option in all_options)
{'1': '/test/1', '3': '/test/3'}
From Python 2.7 and 3 onwards, you can use the dict comprehension syntax:
{option : all_options[option] for option in selected_options if option in all_options}
Or if you just want the values:
>>> [all_options[option] for option in selected_options if option in all_options]
['/test/1', '/test/3']
[option for option in all_options if option in selected_options]
You may want to make a set of selected_options and use that instead if there are many.
How do I get the entries from all_options where the key matches an entry in selected_options?
With a comprehension. We have two kinds: list comprehensions and generator comprehensions.
Note that this depends on what you mean by "entries". If you want a dict with the key/value pairs that match, then you'll need a comprehension that creates the key/value pairs, and then use that to create a dict by feeding it to the dict constructor.
There is a special syntax rule that says that if we call something callable (like, say, a class constructor) with just one argument, and that argument is a generator comprehension, then we only need one pair of parentheses (instead of two: one to call the function and another to mark the comprehension as a comprehension). This lets us write very natural-looking things.
On the other hand, if you just want a list of keys, then you can just use a list comprehension. (You could pass a generator comprehension to the list constructor, too.)
I started down the path of using a List Comprehension...
You have the wrong idea, fundamentally, about how they work. You don't use them to perform an action repeatedly; you use them to calculate a result repeatedly. You wouldn't make an append call in the first part of the statement because (a) the comprehension is already building the sequence for you, so there's no reason to create another empty sequence to append to; (b) the append call returns None after doing the appending, so you end up with a list of None values that you subsequently throw away.
A list comprehension creates a value. A generator comprehension also creates a value, but it's a generator (so you have to extract its values to use them).
So, how do we write the code?
A list of keys looks like this: for each key in the dict (iterating over a dict iterates over its keys), we want that key (with no modification), only if the key is in our other list. That is, we want [key for key in all_options if key in selected_options]. And that's exactly how you write it in Python. A language could hardly read any more naturally while still being unambiguous.
A dict of key-value pairs looks like this: for each key-value pair in the key-value pairs of the dict, we want that pair, only if the key is in our other list. We want to make a dict using those key-value pairs, so we wrap the comprehension in the dict constructor. To get key-value pairs from a dict, we iterate over its .items(). So, we want a dict constructed from a key and value, for each key and value in the items of the original dict, where the key is in the other list. And again, that's exactly what we write: dict((key, value) for (key, value) in all_options if key in selected_options).
In more recent versions of Python, we can also use a "dict comprehension", which is basically syntactic sugar so that we can write something that looks more like the list comprehension.
Use set() instead, and take advantage of the intersection operation:
>>> final = set(all_options.keys()) & set(selected_options)
>>> print(final)
{'1', '3'}
The above only returns the keys, but NullUserException notes that the question may want the value as well, using a dict comprehention:
>>> {x: all_options[x] for x in set(all_options.keys()) & set(selected_options)}
{'1': '/test/1', '3': '/test/3'}
For completeness, here's just the value:
>>> [all_options[x] for x in set(all_options.keys()) & set(select_options)]
['/test/1', '/test/3']
The below is wrong. Using set() iterates over both lists, instead of just one.
Using sets is better assuming the options become large. The conditional list comprehensions check every item in one of the containers, but a set intersection takes advantage of Python's excellent hashing. Even the list comprehension here only looks up the desired keys in all_options.
I'm not sure which exact contents you're trying to return, so I'm giving a couple of choices:
if your trying to return: ['1', '3']
[option for option in all_options if option in selected_options]
OR
if you're trying to return: ['/test/1', '/test/3']
[all_options[option] for option in all_options if option in selected_options]

Categories

Resources