Unable to modify the elements of dict in python - python

I have defined a function called modify which modifies given string. I have a dict called elements which have some strings stored in them. However, I am unable to modify those strings stored in the dict.
x = "abc"
x = modify(x)
This works but when I do;
for element in elements:
element = modify(element)
This does not work. Any idea why? I'm fairly new to python.

You cannot modify the elements of a dict whilst iterating through them.
You'd need to use something like this:
for key in elements:
elements[key] = modify(elements[key])

If you need to apply a function to each member of a dictionary, consider using a dict comprehension:
elements = {k: modify(v) for k, v in elements.items()}
If you are using python 2.7 use elements.iteritems() instead of elements.items().

Related

How to efficiently updating list of dict key-values with list of value in Python

The objective is to update new key-value in a list of dict, whereby the value is from another nested list.
This can be realised via
ls1=[[1,23],[2,34,5]]
ls2=[dict(t=1),dict(t=1)]
all_data=[]
for x,y in zip(ls1,ls2):
y['new']=x
all_data.append(y)
For compactness, I would like to have the for-loop in the form of list comprehension.
all_data=[y.update({'new':x}) for x,y in zip(ls1,ls2)]
But, by doing so, I got a list of None instead. May I know how to resolve this?
This is because .update() returns None, not the updated dictionary. You can bitwise-OR two dictionaries together (Python >= 3.9) to obtain what you want:
all_data = [y | {'new':x} for x,y in zip(ls1,ls2)]
If you need to support Python < 3.9, you can construct a new dictionary from the .items() of the old one instead:
all_data = [dict(y.items(), new=x) for x,y in zip(ls1,ls2)]
Note that both the above solutions leave the original dictionaries unchanged.

accessing values() in collection.Counter as a list

I have this:
lst = [2,2,3,3]
c1 = Counter(lst)
x = c1.values()
I want to know why I get this:
x = dict_values([2, 2])
and what can i do to get this:
x = [2,2]
I want to do this so I can manipulate and compare the data inside, the only way I have found is by doing
x = []
for i in c1.values():
x.append(i)
but I was looking for a more direct way to do this, like
x = c1.values()
I tried looking on the net but I can't find anything
You can turn any iterable (including a dict_values) into a list by passing it to the builtin list constructor:
x = list(c1.values())
Never use builtin names like list or dict as variable names; if you do, like you did here:
list = [2,2,3,3]
you won't be able to use the builtin list any more because you've overwritten its name. You'll need to edit your code to change the name of that variable before trying to use list(c1.values()).
The values returned by calling .values() on a dictionary are wrapped within a dict_values object. You can convert it into a normal list using:
x = list(c1.values())
Or, using your loop logic, but applying it directly to Counter and within a list-comprehension:
x = [v for v in Counter(list).values()]
Also as a general hint I would avoid using the names of python builtins such as list as variable names as that can cause problems and unexpected behaviours.

Navigating nested dictionary

I'm trying to wrap my head around how to navigate a series of dictionaries nested in a list.
For example: mydict = {'first':[{'second':2, 'third':3}, {'fourth':4}]}
When I type mydict.get('first'), I get the whole list.
I can't use indexing to get each individual dictionaries in the list (i.e. mydict.get(['first'][0] returns the whole list, and mydict.get(['first'][1]) returns an IndexError).
mydict.get(['first'][0]['second']) andmydict.get(['first']['second']) return TypeErrors.
So, if I wanted to call 'second' or 'fourth' or assign their values to variables, how would I do it?
For second:
mydict['first'][0]['second]
['first'] returns the array
[0] returns the first object of the array
['second'] gets the 'second' object
Perhaps try reshaping your data to something more convenient?
In your example, mydict isn't a series of dictionaries nested in a list. It is a dictionary that contains lists that, in turn, contain dictionaries.
So assuming you don't know which inner dictionary will contain the key you're looking for, you'd have to iterate over all the entries in the parent dictionary to find it. Something like:
desiredKey = 'second'
for listOfDict in mydict.values():
for childDict in listOfDict:
if desiredKey in childDict:
print(childDict[desiredKey])
This will only work if the key you're looking for is always in the inner most dictionaries.

For loop using str.replace()

New to python, trying to figure out how to replace words using a dict.
It is setup like:
list = {"word1":"word2",
"word3":"word4",
"word5":"word6"
}
I have :
for w in list:
new_list = old_list.replace(w)
Thanks!
As pointed out in the comment, list is a built-in name, and you have overwritten it - this might cause weird behaviour.
Your syntax for creating the dictionary is correct, but let's call it my_dict.
Now what are you trying to do? Your title suggets, that you want to replace substrings and not elements in lists?
Anyway, the for-loop loops over the keys of the dictionary. So inside it you should do my_string.replace(my_dict, my_dict[w])
Alternatively, you can loop over the key-value-pairs: for k, v in my_dict.items(). Inside this loop you can use my_string.replace(k, v)

How to declare and add items to an array in Python?

I'm trying to add items to an array in python.
I run
array = {}
Then, I try to add something to this array by doing:
array.append(valueToBeInserted)
There doesn't seem to be a .append method for this. How do I add items to an array?
{} represents an empty dictionary, not an array/list. For lists or arrays, you need [].
To initialize an empty list do this:
my_list = []
or
my_list = list()
To add elements to the list, use append
my_list.append(12)
To extend the list to include the elements from another list use extend
my_list.extend([1,2,3,4])
my_list
--> [12,1,2,3,4]
To remove an element from a list use remove
my_list.remove(2)
Dictionaries represent a collection of key/value pairs also known as an associative array or a map.
To initialize an empty dictionary use {} or dict()
Dictionaries have keys and values
my_dict = {'key':'value', 'another_key' : 0}
To extend a dictionary with the contents of another dictionary you may use the update method
my_dict.update({'third_key' : 1})
To remove a value from a dictionary
del my_dict['key']
If you do it this way:
array = {}
you are making a dictionary, not an array.
If you need an array (which is called a list in python ) you declare it like this:
array = []
Then you can add items like this:
array.append('a')
Arrays (called list in python) use the [] notation. {} is for dict (also called hash tables, associated arrays, etc in other languages) so you won't have 'append' for a dict.
If you actually want an array (list), use:
array = []
array.append(valueToBeInserted)
Just for sake of completion, you can also do this:
array = []
array += [valueToBeInserted]
If it's a list of strings, this will also work:
array += 'string'
In some languages like JAVA you define an array using curly braces as following but in python it has a different meaning:
Java:
int[] myIntArray = {1,2,3};
String[] myStringArray = {"a","b","c"};
However, in Python, curly braces are used to define dictionaries, which needs a key:value assignment as {'a':1, 'b':2}
To actually define an array (which is actually called list in python) you can do:
Python:
mylist = [1,2,3]
or other examples like:
mylist = list()
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist)
>>> [1,2,3]
You can also do:
array = numpy.append(array, value)
Note that the numpy.append() method returns a new object, so if you want to modify your initial array, you have to write: array = ...
Isn't it a good idea to learn how to create an array in the most performant way?
It's really simple to create and insert an values into an array:
my_array = ["B","C","D","E","F"]
But, now we have two ways to insert one more value into this array:
Slow mode:
my_array.insert(0,"A") - moves all values ​​to the right when entering an "A" in the zero position:
"A" --> "B","C","D","E","F"
Fast mode:
my_array.append("A")
Adds the value "A" to the last position of the array, without touching the other positions:
"B","C","D","E","F", "A"
If you need to display the sorted data, do so later when necessary. Use the way that is most useful to you, but it is interesting to understand the performance of each method.
I believe you are all wrong. you need to do:
array = array[] in order to define it, and then:
array.append ["hello"] to add to it.

Categories