How to Convert Dict to string - python

number_pad = {"b":2,"a":2,"c":2,"x":4,"y":4,"z":4}
My print statement is
print(get_number,('00bx'))
How to get the output like this: 0024.
I tried this:
get_number = ""
for key,val in num_pad.items():
get_number = get_phone_number + str(val)
Is there anyway can relate letters to numbers?

You can use dict.get(...) for your task:
number_pad = {"b":2,"a":2,"c":2,"x":4,"y":4,"z":4}
text = '00bx'
re_text = ""
for t in text:
re_text += str(number_pad.get(t, t))
print(re_text) # output: 0024
Or you can condense it to this:
re_text = "".join(str(number_pad.get(t, t)) for t in text)
print(re_text) # output: 0024

Is this essentially what you are after?
str(number_pad['b']) + str(number_pad['x'])

Maybe you can try the map function with a lambda expression.
number_pad = {'b': 2, 'a': 2, 'c': 2, 'x': 4, 'y': 4, 'z': 4}
print(''.join(map(lambda c: str(number_pad[c]) if c in number_pad.keys() else c, '00bx')))

Related

Removing duplicates using a dictionary

I am writing a function that is supposed to count duplicates and mention how many duplicates are of each individual record. For now my output is giving me the total number of duplications, which I don't want.
i.e. if there are 4 duplicates of one record, it's giving me 4 instead of 1; if there are 6 duplicates of 2 individual records it should give me 2.
Could someone please help find the bug?
Thank you
def duplicate_count(text):
text = text.lower()
dict = {}
word = 0
if len(text) != "":
for a in text:
dict[a] = dict.get(a,0) + 1
for a in text:
if dict[a] > 1:
word = word + 1
return word
else:
return "0"
Fixed it:
def duplicate_count(text):
text = text.lower()
dict = {}
word = 0
if len(text) != "":
for a in text:
dict[a] = dict.get(a,0) + 1
return sum(1 for a in dict.values() if a >= 2)
else:
return "0"
You can do this with set and sum. First set is used to remove all duplicates. This is so we can have as few iterations as possible, as-well-as get an immediate count, as opposed to a "one-at-a-time" count. The set is then used to create a dictionary that stores the amount of times a character repeats. Those values are then used as a generator in sum to sum all the times that the "repeat value" is greater than 1.
def dup_cnt(t:str) -> int:
if not t: return 0
t = t.lower()
d = dict()
for c in set(t):
d[c] = t.count(c)
return sum(v>1 for v in d.values())
print(dup_cnt('aabccdeefggh')) #4
I don't really understand the question you asked.
But I assume you want to get the count or details of each letter's duplication in the text. You can do this, hoping this can help.
def duplicate_count(text):
count_dict = {}
for letter in text.lower():
count_dict[letter] = count_dict.setdefault(letter, 0) + 1
return count_dict
ret = duplicate_count('asuhvknasiasifjiasjfija')
# Get all letter details
print(ret)
#{'a': 5, 's': 4, 'u': 1, 'h': 1, 'v': 1, 'k': 1, 'n': 1, 'i': 4, 'f': 2, 'j': 3}
# Get all letter count
print(len(ret))
# 10
# Get only the letters appear more than once in the text
dedup = {k: v for k, v in ret.items() if v > 1}
# Get only duplicated letter details
print(dedup)
# {'a': 5, 's': 4, 'i': 4, 'f': 2, 'j': 3}
# Get only duplicated letter count
print(len(dedup))
# 5

Printing dictionary without brackets

I'm trying to write a script for an exercise that allows me to sort out the characters on a string and count the highest recurring characters but I can't seem to print out the results in a form of a string as its a tuple. Anyone has any idea on how I could do it would be much appreciated.
import sys
stringInput = (sys.argv[1]).lower()
stringInput = sorted(stringInput)
DictCount = {}
Dictionary = {}
def ListDict(tup, DictStr):
DictStr = dict(tup)
return DictStr
for chars in stringInput:
if chars in Dictionary:
Dictionary[chars] += 1
else:
Dictionary[chars] = 1
ListChar = sorted(Dictionary.items(), reverse=True, key=lambda x: x[1])
Characters = (ListChar[0], ListChar[1], ListChar[2], ListChar[3], ListChar[4])
print(ListDict(Characters, DictCount))
current output:
python3 CountPopularChars.py sdsERwweYxcxeewHJesddsdskjjkjrFGe21DS2145o9003gDDS
{'d': 7, 's': 7, 'e': 6, 'j': 4, 'w': 3}
desired output:
d:7,s:7,e:6,j:4,w:3
create your output in this way:
output = ','.join(f"{k}:{v}" for k, v in ListChar)
print(output)
Output:
e:17,d:7,a:3,b:1,c:1
Or just:
>>> dct = {'d': 7, 's': 7, 'e': 6, 'j': 4, 'w': 3}
>>> ','.join(f'{k}:{v}' for k,v in dct.items())
'd:7,s:7,e:6,j:4,w:3'
Try:
yourDict = {'d': 7, 's': 7, 'e': 6, 'j': 4, 'w': 3}
print(','.join("{}:{}".format(k, v) for k, v in yourDict.items()))
Output:
d:7,s:7,e:6,j:4,w:3
Your code is highly redundant. You could write it in a much more concise way by using collections.Counter to help:
from collections import Counter
# Hard coded stringInput for ease in this test
stringInput = 'sdsERwweYxcxeewHJesddsdskjjkjrFGe21DS2145o9003gDDS'.lower()
c = Counter(stringInput)
ListChar = sorted(c.items(), reverse=True, key=lambda x: x[1])
print(','.join(f"{k}:{v}" for k, v in ListChar[:5]))

Python adding data in multi-dimensional dictionary

while (E > 0):
line = raw_input("enter edges : ")
data = line.split()
mygraph[data[0]] = {data[1] : data[2]} //this line
print mygraph
E-=1
Desired data structure:
mygraph = {
'B': {'A': 5, 'D': 1, 'G': 2}
'A': {'B': 5, 'D': 3, 'E': 12, 'F' :5}}
i want to add multiple entries for same key like
but mycode is taking only one value for one node and then replacing
the entries.How to do that?
You need to first add an empty dictionary for the key data[0] if it doesn't already exist, then add the values to it. Otherwise you just wipe out it out every time you loop.
The two usual ways are either to use setdefault on a normal dictionary:
mygraph.setdefault(data[0], {})[data[1]] = data[2]
or use collections.defaultdict where the default is an empty dictionary:
>>> from collections import defaultdict
>>> mygraph = defaultdict(dict)
>>> edges = [[1, 2, 3], [1, 3, 6]]
>>> for edge in edges:
... mygraph[edge[1]][edge[2]] = edge[3]
>>> mygraph
{1: {2: 3,
3: 6}}
Replace this line:
mygraph[data[0]] = {data[1] : data[2]}
with these:
if not data[0] in mygraph:
mygraph[data[0]] = {}
mygraph[data[0]][data[1]] = data[2]

How to convert coma delimited string into python dictionary?

Please help me with the following issue: I have coma delimited strings and value that related to these strings. The number of comas is unpredictable and can be limited by 6. I have to convert it into python dictionary. For example:
aa.bb.cc 6 => mydict['aa']['bb']['cc']=6
aa.bb.dd.ee 8 = mydict['aa']['bb']['dd']['ee']=8
My python version is 2.7.9
One way to do it is to use defaultdict
from collections import defaultdict as defd
dic = defd(dict)
def create_dict(astr):
keys, val = astr.split(' ')
keys = keys.split('.')
val = int(val)
prevdic = dic
for j, k in enumerate(keys):
if j == len(keys)-1:
prevdic[k] = val
elif k not in prevdic:
prevdic[k] = defd(dict)
prevdic = prevdic[k]
create_dict('aa.bb.cc 6')
create_dict('aa.bb.dd.ee 8')
dic['aa']['bb']['cc'] ## returns 6
dic['aa']['bb']['dd']['ee'] ## returns 8
I'm going to assume you want one dictionary with multiple keys (you do say "a dictionary") :
import re
s1 = 'a.bb.dd.ee 8'
s2 = 'aa.bb.cc 6'
def create_d(s):
fields = re.split(r'[. ]', s)
v = int(fields.pop())
d = { field:v for field in fields }
return d
mydict = create_d(s1)
print mydict
mydict.update(create_d(s2))
print mydict
Gives:
{'a': 8, 'ee': 8, 'dd': 8, 'bb': 8}
{'a': 8, 'aa': 6, 'bb': 6, 'ee': 8, 'dd': 8, 'cc': 6}
You can try following simple code
str1 = 'aa.bb.cc 6'
str2 = 'aa.bb.cc.dd 8'
dictstr = {}
strdelim = str1.split(' ')
dictstr[tuple(strdelim[0].split('.'))] = strdelim[1]
strdelim = str2.split(' ')
dictstr[tuple(strdelim[0].split('.'))] = strdelim[1]
print dictstr
Result
{('aa', 'bb', 'cc'): '6', ('aa', 'bb', 'cc', 'dd'): '8'}

Determining Letter Frequency Of Cipher Text

I am trying to make a tool that finds the frequencies of letters in some type of cipher text.
Lets suppose it is all lowercase a-z no numbers. The encoded message is in a txt file
I am trying to build a script to help in cracking of substitution or possibly transposition ciphers.
Code so far:
cipher = open('cipher.txt','U').read()
cipherfilter = cipher.lower()
cipherletters = list(cipherfilter)
alpha = list('abcdefghijklmnopqrstuvwxyz')
occurrences = {}
for letter in alpha:
occurrences[letter] = cipherfilter.count(letter)
for letter in occurrences:
print letter, occurrences[letter]
All it does so far is show how many times a letter appears.
How would I print the frequency of all letters found in this file.
import collections
d = collections.defaultdict(int)
for c in 'test':
d[c] += 1
print d # defaultdict(<type 'int'>, {'s': 1, 'e': 1, 't': 2})
From a file:
myfile = open('test.txt')
for line in myfile:
line = line.rstrip('\n')
for c in line:
d[c] += 1
For the genius that is the defaultdict container, we must give thanks and praise. Otherwise we'd all be doing something silly like this:
s = "andnowforsomethingcompletelydifferent"
d = {}
for letter in s:
if letter not in d:
d[letter] = 1
else:
d[letter] += 1
The modern way:
from collections import Counter
string = "ihavesometextbutidontmindsharing"
Counter(string)
#>>> Counter({'i': 4, 't': 4, 'e': 3, 'n': 3, 's': 2, 'h': 2, 'm': 2, 'o': 2, 'a': 2, 'd': 2, 'x': 1, 'r': 1, 'u': 1, 'b': 1, 'v': 1, 'g': 1})
If you want to know the relative frequency of a letter c, you would have to divide number of occurrences of c by the length of the input.
For instance, taking Adam's example:
s = "andnowforsomethingcompletelydifferent"
n = len(s) # n = 37
and storing the absolute frequence of each letter in
dict[letter]
we obtain the relative frequencies by:
from string import ascii_lowercase # this is "a...z"
for c in ascii_lowercase:
print c, dict[c]/float(n)
putting it all together, we get something like this:
# get input
s = "andnowforsomethingcompletelydifferent"
n = len(s) # n = 37
# get absolute frequencies of letters
import collections
dict = collections.defaultdict(int)
for c in s:
dict[c] += 1
# print relative frequencies
from string import ascii_lowercase # this is "a...z"
for c in ascii_lowercase:
print c, dict[c]/float(n)

Categories

Resources