I have list and i want to replace all the elements os the list with another elements.
Code:
list1 = ['1','1','3','4','5','2','3','4']
dict1 = {'dict1' : ['1','2','3','4','5'] ,'name':['su5','pra4','sa3','ma2','sri1']}
for x in range(len(dict1['dict1'])):
list1 = [word.replace(dict1['dict1'][x],dict1['name'][x]) for word in list1]
print(list1)
Actual Output:
['susri1', 'susri1', 'sa3', 'ma2', 'sri1', 'prama2', 'sa3', 'ma2']
Expected Output:
['su5','su5','sa3','ma2','sri1','pra4','sa3','ma2']
That's a very strange dictionary if you transform the dictionary so you can use it as a direct mapping then this is a relatively easy thing to do, e.g.:
>>> dict2 = dict(zip(dict1['dict1'], dict1['name']))
>>> [dict2[i] for i in list1]
['su5', 'su5', 'sa3', 'ma2', 'sri1', 'pra4', 'sa3', 'ma2']
Related
I was learning Python and came upon a problem: To convert a list of list to dictionary based on a certain key.
If the input is: [['key1','h1'],['key2','h2'],['key3','h3'],['key1','h4'],['key1','h5'], ['key2','h6']]
The output is: {'key1':{'h1','h4','h5'}, 'key2':{'h2', 'h6'}, 'key3':{'h3'}}
The logic being, the first element of the inner array is considered as the key for the new dictionary.
I am currently doing it the dirty way by iterating over the entire list. But, is there a better way to do it?
You'll have to iterate over the list. One way is to use dict.setdefault:
out = {}
for k,v in lst:
out.setdefault(k, set()).add(v)
This is the same as the following conditional loop:
out = {}
for k,v in lst:
if k in out:
out[k].add(v)
else:
out[k] = {v}
Output:
{'key1': {'h1', 'h4', 'h5'}, 'key2': {'h2', 'h6'}, 'key3': {'h3'}}
I am adding below readable code for creating a 'list' and all methods of add element. Here is the code:
Create list. Add element using append(),insert()
# Create lists
list1 = [1,4,6,8] # integer list.
list2 = [] # Empty List.
list3 = [1.2,'Raj',1] # mixed list.
# Print Created lists
print(list1)
print(list2)
print(list3)
# Add element using append(). Elements will be added at the last of list.
list1.append(11)
list1.append(12)
print(list1)
# Add elements in an empty list using for loop and append()
list2 = []
string = 'abcdef'
for ele in string:
list2.append(ele)
print(list2)
# Add element using insert(). Element will add at any position using index
list4 = ['r','j','s','h']
list4.insert(1,'a')
list4.insert(3,'e')
print(list4)
i have shared the link of image where both input and output is shown
I have a huge list like
list = [["a", "bfgf", "c%2"], ["b", "hhj", "kkkk", "f%2"]]
I want to remove %2 end of every last item in lists of list.
I tried
list = [[item[-1].replace('%2', '') for item in lst] for lst in list]
and it did not work
Your way does not work because you are not changing the value in place. Your statement simply takes a copy of every sub-list, stores it in lst, then changes the data in that copy, and not the actual list itself.
Try it in this way, and tell me if it works.
myList= [["a","bfgf","c%2"],["b","hhj","kkkk","f%2"]]
for i in range(len(myList)):
Last=myList[i].pop()
Last=Last.replace("%2","")
myList[i].append(Last)
print (myList)
For your nested list you can also use a nested list comprehension to remove the unwanted characters.
ini_list = [["a", "bfgf", "c%2"],["b", "hhj", "kkkk", "f%2"]]
ini_list = [[val.replace('%2', '') for val in sublist] for sublist in ini_list]
print(ini_list)
# output
[['a', 'bfgf', 'c'], ['b', 'hhj', 'kkkk', 'f']]
I am trying to create a dictionary of codes that I can use for queries and selections. Let's say I have a dictionary of state names and corresponding FIPS codes:
statedict ={'Alabama': '01', 'Alaska':'02', 'Arizona': '04',... 'Wyoming': '56'}
And then I have a list of FIPS codes that I have pulled in from a Map Server request:
fipslist = ['02121', '01034', '56139', '04187', '02003', '04023', '02118']
I want to sort of combine the key from the dictionary (based on the first 2 characters of the value of that key) with the list items (also, based on the first 2 characters of the value of that key. Ex. all codes beginning with 01 = 'Alabama', etc...). My end goal is something like this:
fipsdict ={'Alabama': ['01034'], 'Alaska':['02121', '02003','02118'], 'Arizona': ['04187', '04023'],... 'Wyoming': ['56139']}
I would try to set it up similar to this, but it's not working quite correctly. Any suggestions?
fipsdict = {}
tempList = []
for items in fipslist:
for k, v in statedict:
if item[:2] == v in statedict:
fipsdict[k] = statedict[v]
fipsdict[v] = tempList.extend(item)
A one liner with nested comprehensions:
>>> {k:[n for n in fipslist if n[:2]==v] for k,v in statedict.items()}
{'Alabama': ['01034'],
'Alaska': ['02121', '02003', '02118'],
'Arizona': ['04187', '04023'],
'Wyoming': ['56139']}
You will have to create a new list to hold matching fips codes for each state. Below is the code that should work for your case.
for state,two_digit_fips in statedict.items():
matching_fips = []
for fips in fipslist:
if fips[:2] == two_digit_fips:
matching_fips.append(fips)
state_to_matching_fips_map[state] = matching_fips
>>> print(state_to_matching_fips_map)
{'Alabama': ['01034'], 'Arizona': ['04187', '04023'], 'Alaska': ['02121', '02003', '02118'], 'Wyoming': ['56139']}
For both proposed solutions I need a reversed state dictionary (I assume that each state has exactly one 2-digit code):
reverse_state_dict = {v: k for k,v in statedict.items()}
An approach based on defaultdict:
from collections import defaultdict
fipsdict = defaultdict(list)
for f in fipslist:
fipsdict[reverse_state_dict[f[:2]]].append(f)
An approach based on groupby and dictionary comprehension:
from itertools import groupby
{reverse_state_dict[k]: list(v) for k,v
in (groupby(sorted(fipslist), key=lambda x:x[:2]))}
The following python 3 code results in the tuple ('bla', 1.0) being added to both list1 and list2. Why? They don't point to the same place in memory.
#copy list1 to new list2:
for c in list1:
list2.append(c)
#loop through list1 and extend list2
>>> for idxc, c in enumerate(list1):
... for idxsc, sc in enumerate(c):
... list2[idxc][idxsc].extend([tuple(('bla', 1.0))])
The way to make a true copy of a list and all its contents, that will work on nested lists is by making a deep copy:
import copy
list2 = copy.deepcopy(list1)