I need to replace dictionary values based on their index
Ex:
mydict = {'abc':10, 'iji':9, 'sls': 8, 'eie': 2, 'wlw': 6, 'pwp': 5}
Here i need to replace the value of the key at 4th index with new value 10
Expected output:
{'abc':10, 'iji':9, 'sls': 8, 'eie': 2, 'wlw': 10, 'pwp': 5}
You can use dict.keys() to get the keys of the dictionary, then find the key at the 4th index of that list and set that value in the dictionary:
mydict = {'abc':10, 'iji':9, 'sls': 8, 'eie': 2, 'wlw': 6, 'pwp': 5}
keys = list(mydict.keys())
mydict[keys[4]] = 10
print(mydict)
Output:
{'abc': 10, 'iji': 9, 'sls': 8, 'eie': 2, 'wlw': 10, 'pwp': 5}
Note
This will only work in Python < 3.7 if the dictionary is not modified (entries added or deleted after creation) as otherwise mydict.keys() is not guaranteed to return the same order of result each time. For versions of Python < 3.7 it is safer to use an OrderedDict.
Related
I have the following frozenset:
f_set = [frozenset({8, 14, 15, 18}), frozenset({1, 2, 3, 7, 8}), frozenset({0, 4, 5})]
I need to convert f_set into a dictionary as the following
For the first set, I need the dictionary to have a value of 0.
For the second set, I need the dictionary to have a value of 1.
For the third set, I need the dictionary to have a value of 2.
Now, in case some keys are existed in multiple set, assign a new values to them. In this case 8 existed in both set 1 and set 2, so assign a value of 3.
dict1 = {8:3, 14:0, 15:0, 18:0, 1:1, 2:1, 3:1, 7:1, 0:2, 4:2, 5:2}
Note: my actual f_set contains more than three sets, so I'd like to avoid doing that manually.
You can use dict comprehension with enumerate:
f_set = [frozenset({8, 14, 15, 18}), frozenset({1, 2, 3, 7, 8}), frozenset({0, 4, 5})]
dict1 = {x: i for i, s in enumerate(f_set) for x in s}
print(dict1)
# {8: 1, 18: 0, 14: 0, 15: 0, 1: 1, 2: 1, 3: 1, 7: 1, 0: 2, 4: 2, 5: 2}
Note that, if the sets are not mutually disjoint, some keys will be discarded, since a dict cannot have duplicate keys.
You can simply loop over the frozensets to set each of them in an output dictionary:
output = dict()
for i in range(len(f_set)):
for s in f_set[i]:
output[s] = i
Note although the order may be different from what you have, order shouldn't matter in the dictionary.
I want to create a new dict with a loop but I don't find the way to push key and value in loop with append. I try something like this but I'm still searching the good way.
frigo = {"mangue" : 2, "orange" : 8, "cassoulet" : 1, "thon" : 2, "coca" : 8, "fenouil" : 1, "lait" : 3}
new_frigo = {}
for i, (key, value) in enumerate(frigo.items()):
print(i, key, value)
new_frigo[i].append{key,value}
There's already a python function for that:
new_frigo.update(frigo)
No need for a loop! dict.update(other_dict) just goes and adds all content of the other_dict to the dict.
Anyway, if you wanted for some reason to do it with a loop,
for key, value in frigo.items():
new_frigo[key] = value
would do that. Using an i here makes no sense - a dictionary new_frigo doesn't have indices, but keys.
You can use update to append the key and values in the dictionary as follows:
frigo = {"mangue": 2, "orange": 8, "cassoulet": 1, "thon": 2, "coca": 8, "fenouil": 1, "lait": 3}
new_frigo = {}
for (key, value) in frigo.items():
new_frigo.update({key:value})
print(new_frigo)
Result:
{'mangue': 2, 'orange': 8, 'cassoulet': 1, 'thon': 2, 'coca': 8, 'fenouil': 1, 'lait': 3}
I have a nested dict that looks like:
{KeyA: {'ItemA': 1, 'ItemB': 2, 'ItemC': 3, 'ItemD': 4, 'ItemE': 5, 'ItemF': 6},
{KeyB: {'ItemR': 2, 'ItemQ': 3, 'ItemG': 4, 'ItemZ': 5, 'ItemX': 6, 'ItemY': 7}
I would like to output this to a csv where the desired row format is:
ItemA, 1, Item B, 2, ItemC, 3, ItemD, 4, ItemE, 5, ItemF, 6
I've managed to get a row that's keys and then another below it with the associated value with the below code:
for item in myDict:
item = myDict[x]
itemVals = item.values()
wr.writerow(item)
wr.writerow(itemVals)
x += 1
I've tried a number of ways of reformatting this and keep running into subscriptable errors every which way I try.
The length of the top level dict could be large, up to 30k nested dicts. The nested dicts are a constant length of 6 key:value pairs, currently.
What's a clean way to achieve this?
Here is an implementation with loops:
myDict = {'KeyA': {'ItemA': 1, 'ItemB': 2, 'ItemC': 3, 'ItemD': 4, 'ItemE': 5, 'ItemF': 6},
'KeyB': {'ItemR': 2, 'ItemQ': 3, 'ItemG': 4, 'ItemZ': 5, 'ItemX': 6, 'ItemY': 7}}
with open("output.csv", "w") as file:
for key in myDict:
for nestedKey in myDict[key]:
file.write(key + "," + str(myDict[key][nestedKey]) + ",")
file.write("\n")
output.csv:
KeyA,1,KeyA,2,KeyA,3,KeyA,4,KeyA,5,KeyA,6,
KeyB,2,KeyB,3,KeyB,4,KeyB,5,KeyB,6,KeyB,7,
I have a dictionary users with 1748 elements as (showing only the first 12 elements)-
defaultdict(int,
{'470520068': 1,
'2176120173': 1,
'145087572': 3,
'23047147': 1,
'526506000': 1,
'326311693': 1,
'851106379': 4,
'161900469': 1,
'3222966471': 1,
'2562842034': 1,
'18658617': 1,
'73654065': 4,})
and another dictionary partition with 452743 elements as(showing first 42 elements)-
{'609232972': 4,
'975151075': 4,
'14247572': 4,
'2987788788': 4,
'3064695250': 2,
'54097674': 3,
'510333371': 0,
'34150587': 4,
'26170001': 0,
'1339755391': 3,
'419536996': 4,
'2558131184': 2,
'23068646': 6,
'2781517567': 3,
'701206260771905541': 4,
'754263126': 4,
'33799684': 0,
'1625984816': 4,
'4893416104': 3,
'263520530': 3,
'60625681': 4,
'470528618': 3,
'4512063372': 6,
'933683112': 3,
'402379005': 4,
'1015823005': 2,
'244673821': 0,
'3279677882': 4,
'16206240': 4,
'3243924564': 6,
'2438275574': 6,
'205941266': 3,
'330723222': 1,
'3037002897': 0,
'75454729': 0,
'3033154947': 6,
'67475302': 3,
'922914019': 6,
'2598199242': 6,
'2382444216': 3,
'1388012203': 4,
'3950452641': 5,}
The keys in users(all unique) are all in partition and also are repeated with different values(and also partition contains some extra keys which is not of our use). What I want is a new dictionary final which connects the keys of users matching with those of partition with the values of partition, i.e. if I have '145087572' as a key in users and the same key has been repeated twice or thrice in partition with different values as: {'145087572':2, '145087572':3,'145087572':7} then I should get all these three elements in the new dictionary final. Also I have to store this dictionary as a key:value RDD.
Here's what I tried:
user_key=list(users.keys())
final=[]
for x in user_key:
s={x:partition.get(x) for x in partition}
final.append(s)
After running this code my laptop stops to respond (the code still shows [*]) and I have to restart it. May I know that is there any problem with my code and a more efficient way to do this.
First dictionary cannot hold duplicate keys, duplicate key's value will be ovewritten by the last value of same key.
Now lets analyze your code
user_key=list(users.keys()) # here you get all the keys say(1,2,3)
final=[]
for x in user_key: #you are iterating over the keys so x will be 1, 2, 3
s={x:partition.get(x) for x in partition} #This is the reason for halting
''' breaking the above line this is what it looks like.
s = {}
for x in partition:
s[x] = partition.get(x)
isn't the outer forloop and inner forloop is using the same variable x
so basically instead of iterating over the keys of users you are
iterating over the keys of partition table,
as x is updated inside inner foorloop(so x contains the keys of partition
table).
'''
final.append(s)
Now the reason for halting is (say you have 10 keys in users dictionary).
so outer forloop will iterate 10 times and for the 10 times
Inner forloop will iterate over whole partition keys and make a copy
which is causing memory error and eventually your system gets hung due to out of memory.
I think this will work for you
store partition data in a python defaultdict(list)
from collections import defaultdict
user_key = users.keys()
part_dict = defaultdict(list)
# partition = [[key1, value], [key2, value], ....]
# store your parition data in this way (list inside list)
for index in parition:
if index[0] not in part_dict:
part_dict[index[0]] = index[1]
else:
part_dict[index[0]].append(index[1])
# part_dict = {key1:[1,2,3], key2:[1,2,3], key3:[4,5],....}
final = []
for x in user_keys:
for values in part_dict[x]:
final.append([x, values])
# if you want your result of dictionary format(I don't think it's required) then you ca use
# final.append({x:values})
# final = [{key1: 1}, {key2: 2}, ....]
# final = [[key1, 1], [key1, 2], [key1, 3], .....]
The above code is not tested, some minor changes may be required
Here is a list a=[1,1,1,2,4,2,4,32,1,4,35,23,24,23]
I do this in python:
unique_number=list(set(a))
ans=map(lambda x:a.index(x),unique_number)
output:
<map at 0x2b98b307828>
I want to know what's wrong with my code and find an more efficient way to achieve this.
This code would work as you expected in Python 2. In Python 3, map returns an iterator. You could, e.g., convert it to a list:
>>> ans=map(lambda x:a.index(x),unique_number)
>>> list(ans)
[7, 0, 3, 10, 4, 11, 12]
You can avoid keep re-indexing and building a set first - simply build a dict iterating over a backwards as the dictionary will only keep the last value for a key (in this case - the earliest appearing index), eg:
a=[1,1,1,2,4,2,4,32,1,4,35,23,24,23]
first_index = {v:len(a) - k for k,v in enumerate(reversed(a), 1)}
# {1: 0, 2: 3, 4: 4, 23: 11, 24: 12, 32: 7, 35: 10}
This way you're only scanning the sequence once.
Try this:
for value in map(lambda x:a.index(x),unique_number):
print(value)
or append this:
for var in ans:
print(var)