Appending an integer to dictionary keys, python - python

I have a python dictionary with several keys.
Example:
dicOut = dict(list(zip(keys, values)))
for i in keys:
print(i)
out:
Trees
Cars
People
.... x n keys
I wish to assign a number in front.
Trees
Cars
People
.... x n keys
How do I make the for loop"
so far:
k = len(keys)
x = range (1,k+1)
for j in x:
for k in keys:
n= j, '-', k
print(n)
However it print all e.g. 3 keys 3 time. How to stop it at just e.g. e distinct keys.

for key in dict:
print(key, '. ', dict[key])

for i,k in enumerate(dicOut, start=1):
print(i,k)

Related

A python program to filter dictionary

Write a python program to filter a dictionary based on values that are the multiples of 6
NOTE:
Take keys as strings and values as integers.
Constraints:
1<=number of key value pairs<=10
Sample test case: keys : a,b,c,d,e,f values:1,2,3,4,5,6 {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6} {'f':6}
You can use a dict comprehension.
d = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}
res = {k:v for k,v in d.items() if v % 6 == 0}
print(res)
old_dict = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}
#or this it will work totally perfect
#old_dict = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13}
print (f"Original dictionary is : {old_dict}")
print()
new_dict = {key:value for (key, value) in old_dict.items() if value % 6 == 0}
print(f"New dictionary with multiple of 6 is : {new_dict}")

Iterate over dict from value to value

I have a dictionary like this :
data = {1: [u'-', u's'], 2: [u'je', u'co', u'na'], ...}
The KEY is the LENGTH of the words that belong to it. I want to call a function (that will count levenshtein distance) for words that are longer than X and shorter than Y. How would I do it ?
The main problem is getting the dictionary length because len() returns the number of items in the dictionary, not keys.
Now I am doing it like this:
for k in data:
if k >= len(word)-distance and k <= len(word)+distance:
for item in data[k]:
if levenshtein(word, item) == distance:
words.append(item)
return words
data.keys() will give you the keys, you can iterate over them.
You can get a list of all words with length between X and Y with
sum((words for key, words in data.items() if X<key<Y), [])

python select the lowest alphanumeric value with a reference from multiple lists

I have multiple lists like this:
#Symbol ID
['AAA','MG_00013']
['AAA','MG_00177']
['AAA','MG_00005']
['BBB','MG_0045']
['BBB','MG_00080']
['CCC','MG_0002'] # and so on...
and I would like to choose the list with a same symbol with the smallest ID.
So, the end result is like this:
#Symbol ID
['AAA','MG_00005']
['BBB','MG_0045']
['CCC','MG_0002'] #...
To do that, I have made them into a list of lists
listoflists =[['AAA','MG_00013'],['AAA','MG_00177'],['AAA','MG_00005'],['BBB','MG_0045'],['BBB','MG_00080'],['CCC','MG_0002']]
I'm lost from here...
for i in listoflists:
if i[0] == i[0]:
test.append(i[1])
for i in test:
print(i)
which gives a False result.
I think the logic is to make them into a list like the below and compare the alphanumeric ID and select the lowest one.
[(AAA,['MG_00013','MG_00177','MG_00005'])]
However, I'm completely lost and frustrating now...
Could you ,please, help me go through this?
===============================================
Everybody helping me out is so great!
However, the length of ID have to be considered.
For example, everybody gives me BBB wih MG_00080, but it suppose MG_0045 as 45 is less than 80...
I would think something like a dictionary might be better, but this will give your expected output.
import itertools
listoflists =[['AAA','MG_00013'],['AAA','MG_00177'],['AAA','MG_00005'],['BBB','MG_0045'],['BBB','MG_00080'],['CCC','MG_0002']]
minlists = [
min(value, key=lambda lst: lst[1])
for _, value in itertools.groupby(listoflists, lambda lst: lst[0])
]
print minlists
outputs
[['AAA', 'MG_00005'], ['BBB', 'MG_00080'], ['CCC', 'MG_0002']]
EDIT: The comparison of ids was not clear to me, but to compare them psuedo-numerically (not lexiographically), replace key=lambda lst: lst[1] with
key=lambda lst: int(lst[1][3:])
This is a good spot for a defaultdict
from collections import defaultdict
D = defaultdict(list)
for k,v in listoflists:
D[k].append(v)
return [[k, min(D[k])] for k in D]
ll =[['AAA','MG_00013'],
['AAA','MG_00177'],
['AAA','MG_00005'],
['BBB','MG_0045'],
['BBB','MG_00080'],
['CCC','MG_0002']]
d = {}
for l in ll:
# If key is not the dict, insert the entry into dict
if l[0] not in d:
d[l[0]] = l[1]
# If key is already in the dict, update the entry if value is smaller
elif int(l[1][3:]) < int(d[l[0]][3:]):
d[l[0]] = l[1]
print d
Output:
{'AAA': 'MG_00005', 'BBB': 'MG_0045', 'CCC': 'MG_0002'}
You could convert it into the dictionary of lists
d = { k[0] : [] for k in listoflists }
for k in listoflists: d[k[0]].append(k[1])
ans = [ [k,min(d[k])] for k in d ]
print ans
or just
d = { k[0] : [] for k in listoflists }
for k in listoflists: d[k[0]].append(k[1])
for k in d: print k,min(d[k])

Python: While Statement = Statement Print associated Values

In Python I currently have a Dictionary with a composite Key. In this dictionary there are multiple occurences of these keys. (The keys are comma-separated):
(A,B), (A,C), (A,B), (A,D), (C,A), (A,B), (C,A), (C,B), (C,B)
I already have something that totals the unique occurrences and counts the duplicates which gives me a print-out similar to this:
(A,B) with a count of 4, (A,C) with a count of 2, (B,C) with a count of 6, etc.
I would like to know how to code a loop that would give me the following:
Print out the first occurance of the first part of the key and its associtated values and counts.
Name: A:
Type Count
B 4
C 2
Total 6
Name: B:
Type Count
A 3
B 2
C 3
Total 8
I know I need to create a loop where the first statement = the first statement and do the following, but have no real idea how to approach/code this.
Here's a slightly slow algorithm that'll get it done:
def convert(myDict):
keys = myDict.keys()
answer = collections.defaultdict(dict)
for key in keys:
for k in [k for k in keys if k.startswith(key[0])]:
answer[key[0]][k[1]] = myDict[k]
return answer
Ultimately, I think what you're after is a trie
Its a little misleading to say that your dictionary has multiple values for a given key. Python doesn't allow that. Instead, what you have are keys that are tuples. You want to unpack those tuples and rebuild a nested dictionary.
Here's how I'd do it:
import collections
# rebuild data structure
nested = collections.defaultdict(dict)
for k, v in myDict.items():
k1, k2 = k # unpack key tuple
nested[k1][k2] = v
# print out data in the desired format (with totals)
for k1, inner in nested.items():
print("%s\tType\tCount" % k1)
total = 0
for k2, v in innner.items():
print("\t%s\t%d" % (k2, v))
total += v
print("\tTotal\t%d" % total)

Python List Exclusions

I have a dictionary of lists with info such as var1=vara, var1=varb, var2=vara etc. This can have lots of entries, and I print it out ok like this
for y in myDict:
print(y+"\t"+myDict[y])
I have another list which has exclusions in like this var2, var3 etc. This may have < 10 entries and I can print that ok like this
for x in myList:
print(x)
Now I want to remove occurrences of key val pairs in the dictionary where the keys are the list values. I tried this
for x in myList:
for y in myDict:
if x != y: print(y+"\t"+myDict[y])
but on each pass through the list it lets all the others apart from the current `x to the screen
Is there a nice python way to remove the key val pairs from the dictionary if the key exists in the list?
Do you mean
for key in myDict:
if key not in myList:
print(key+"\t"+myDict[key])
Or one of many alternatives:
for key in (set(myDict)-set(myList)):
print(key+"\t"+myDict[key])
mySet = set(myList)
myNewDict = dict(((k, v) for k, v in myDict if k not in mySet))
Note that using mySet instead of myList isn't a concern unless myList has a large number of entries.

Categories